我们正在对我们的服务进行单元测试,并面临使用依赖服务参数监视方法的问题。
我正在为 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';
}
}
而且我不确定在这种情况下测试承诺。