我有myService
那个用途myOtherService
,它可以进行远程调用,并返回promise:
angular.module('app.myService', ['app.myOtherService'])
.factory('myService', [
myOtherService,
function(myOtherService) {
function makeRemoteCall() {
return myOtherService.makeRemoteCallReturningPromise();
}
return {
makeRemoteCall: makeRemoteCall
};
}
])
要对myService
我进行单元测试,需要模拟myOtherService
,以使其makeRemoteCallReturningPromise
方法返回promise。这是我的方法:
describe('Testing remote call returning promise', function() {
var myService;
var myOtherServiceMock = {};
beforeEach(module('app.myService'));
// I have to inject mock when calling module(),
// and module() should come before any inject()
beforeEach(module(function ($provide) {
$provide.value('myOtherService', myOtherServiceMock);
}));
// However, in order to properly construct my mock
// I need $q, which can give me a promise
beforeEach(inject(function(_myService_, $q){
myService = _myService_;
myOtherServiceMock = {
makeRemoteCallReturningPromise: function() {
var deferred = $q.defer();
deferred.resolve('Remote call result');
return deferred.promise;
}
};
}
// Here the value of myOtherServiceMock is not
// updated, and it is still {}
it('can do remote call', inject(function() {
myService.makeRemoteCall() // Error: makeRemoteCall() is not defined on {}
.then(function() {
console.log('Success');
});
}));
从上面可以看到,我的模拟的定义取决于$q
,我必须使用来加载inject()
。此外,应该在中进行注入模拟module()
,这应该在之前进行inject()
。但是,更改模拟后,其值不会更新。
正确的方法是什么?
myService.makeRemoteCall()
吗?如果是这样,问题就在于myService
没有,makeRemoteCall
与您的嘲笑无关myOtherService
。