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

时间:2016-01-19 23:07:40

标签: angularjs jasmine karma-runner sinon

我使用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;
            }
        };
    }
}());

当我运行测试时,它失败并说:

  

预期的间谍" testMethod"被称为。 " TestMethod的"被叫了0次。

奇怪的是,如果我从测试文件中添加一个test属性,例如:

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组合,一切都按预期工作。不确定为什么没有调用存根?

1 个答案:

答案 0 :(得分:1)

此时

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

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

相关问题