0

我们正在对我们的服务进行单元测试,并面临使用依赖服务参数监视方法的问题。

我正在为 ServiceA 编写单元测试

服务A.js

angular.module("App").service("ServiceA", function($http, ServiceB) {
    this.detail = null; 
    this.method = function(id){
        var sevrB = new ServiceB();
        return sevrB.getId(1).then(function(response) {
            this.detail = response.data;
        }); 
    };
 });

ServiceB.js(是工厂)

(function () {
    var dependencies = [
      '../module'
    ];
    define(dependencies, function (module) {
        return module.factory('ServiceB', function ($http) {
            var ServiceB= function () {
                this.id = null;               
            };

        ServiceB.prototype.getId = function(Id) {                               
            return $http.get('/test/');
        }
    }
 }());

单元测试代码

 describe('Testing ServiceA', function () {
 var serviceA, serviceBMock;

 beforeEach(function () {
     var _serviceBMock = function () {
         return {
             getId:function(id){
                 return 'test';
             }
         };
     };

     angular.module('ServiceAMocks', [])                   
         .value('ServiceB', _serviceBMock);
 });

beforeEach(module('ServiceAMocks'));       

beforeEach(inject(function (_ServiceA_, _ServiceB_) {
    serviceA=_ServiceA_;
    serviceBMock=_ServiceB_;
});

it('retrive Id', function () {  
   spyOn(serviceBMock,'getId').and.Return('test');
   serviceA.method(1);
});

}); 

我正在从 ServiceA 监视 ServiceB 的 getId 方法,如果我将 ServiceB 模拟为函数,我会在下面收到错误

错误:jasmineInterface.spyOn 中不存在 getId() 方法

如果我将 serviceB 模拟为对象,那么我会收到错误消息

 TypeError: object is not a function

 var _serviceBMock = {              
     getId:function(id){
         return 'test';
     }
 }

而且我不确定在这种情况下测试承诺。

4

1 回答 1

0

此版本支持 Jasmine 1.3

我正在注入 $q 服务,因为 ServiceB 想要调用方法。我们甚至可以继续解决返回的承诺,但这是测试的下一步。

回答以前版本的问题,AngularJS 注入serviceB的实例

describe('ServiceA', function () {
    var serviceA, ServiceB, $q;

    beforeEach(function () {
        module('App');
    });

    beforeEach(function () {
        module(function ($provide) {
            $provide.value('ServiceB', {
                getId: jasmine.createSpy('ServiceB.getId').andCallFake(function () {
                    return $q.all();
                })
            });
        });
    });

    beforeEach(inject(function (_ServiceA_, _ServiceB_, _$q_) {
        $q = _$q_;
        serviceA = _ServiceA_;
        ServiceB = _ServiceB_;
    }));

    describe('.method()', function () {
        it('returns ServiceB.getId() argument', function () {
            serviceA.method(1);
            expect(ServiceB.getId).toHaveBeenCalledWith(1);
        });
    });
});

jsfiddle:http: //jsfiddle.net/krzysztof_safjanowski/sDh35/

于 2014-08-03T23:45:06.040 回答