AngularJS:模拟控制器服务

时间:2015-01-26 16:08:37

标签: angularjs unit-testing

我正在尝试为控制器模拟一项服务,但却努力让它发挥作用。

使用半psudeo代码我有一个服务:

.factory('SomeService', ['$http'function($http) {

    var someService = {};

    someService.getData=function(val1, val2){
        ...
        return someData;
    }

    return someService;
}

和控制器一样:

 .controller('someController', ['SomeService', function(SomeService){
    var self = this;
    var data = [];

    self.getSomeData = = function(){
         var response = SomeService.getSomething.then(function(response){
              self.data = response;
         });
    };
 }]);

我正在尝试编写一个使用$ provide来模拟服务的测试。像这样:

var mockService

beforeEach(module(function($provide){
    mockService.getSomething = function(){ 

            return   [ ....];
    };

    $provide.value('SomeService', mockService);

}));

注入此模拟并运行测试后,我得到:

Typeerror:无法设置属性getSomething of undefined

此代码(或右侧)是否有任何明显错误?

1 个答案:

答案 0 :(得分:0)

您需要将mockService作为对象:

describe('Some Service', function(){
    var mockService;

    beforeEach(module(function($provide){
        mockService = {
            getSomething: function () {
                return {
                    then: function (success, error) {
                        success(true);
                    }
                };
            }
        };
        $provide.value('SomeService', mockService);
    }));
});

我建议您浏览the docs,因为它们非常有帮助。