AngularJs 服务上的 Sinon 存根未按预期工作

Sinon stub on AngularJs service not working as expected

我正在使用 Karma、Jasmine 和 Sinon 来测试 AngularJs 应用程序。一个控制器注入了一个服务,我想使用 Sinon 沙箱在该服务上存根一个方法。这是控制器:

(function () {
    'use strict';

    angular.module('app').controller('myController', myController);

    myController.$inject = ['$scope', 'myService'];

    function myController($scope, myService) {

        $scope.methodTestResult = myService.testMethod();
    }
}());

这里是测试文件:

(function () {
    'use strict';

    beforeEach(module('app'));

    describe('myController', function () {

        var $scope, myService;

        beforeEach(inject(function ($controller, $rootScope, _myService_) {
            $scope = $rootScope.$new();

            myService = _myService_;

            $controller('myController', { $scope: $scope });

            sandbox = sinon.sandbox.create();

        }));

        afterEach(function () {
            sandbox.restore();
        });

        describe('methodTestResult', function () {

            beforeEach(function () {
                sandbox.stub(myService, 'testMethod');
            });

            it('invokes the testMethod', function () {
                expect(myService.testMethod).toHaveBeenCalled();
            });
        });
    });

}());

FWIW,这里是服务工厂:

(function () {
    'use strict';

    angular.module('app').factory('myService', myService);

    function myService() {  
        return {
            testMethod: function () {
                return true;
            }
        };
    }
}());

当我 运行 测试失败并显示:

Expected spy "testMethod" to have been called. "testMethod" was called 0 times.

奇怪的是,如果我从测试文件中向服务添加测试 属性,例如:

myService.testProperty = 'test';

然后从正在测试的控制器中注销:

console.log(myService.testProperty);

这按预期工作,我可以看到控制器内的测试文件中添加了新的 属性。我在我的业力配置中将 sinon 指定为一个框架,没有关于缺少依赖项的错误被抛出。以下是我安装的软件包:

"grunt": "^0.4.5"
"grunt-karma": "^0.12.1",
"jasmine-core": "^2.4.1",
"jasmine-sinon": "^0.4.0",
"karma": "^0.13.19",
"karma-jasmine": "^0.3.6",
"karma-phantomjs-launcher": "^0.2.3",
"karma-sinon": "^1.0.4",
"phantomjs": "^1.9.19",
"sinon": "^1.17.2"

我以前使用过相同的 AngularJs/Karma/Jasmine/Sinon 组合,一切都按预期工作。不确定为什么不调用存根?

此时

       $controller('myController', { $scope: $scope });

'myController' 构造函数已经被调用,因此原始 myService.testMethod 方法。解决方案是在控制器实例化之前对其进行存根。