最佳答案
我有使用 myOtherService
的 myService
,它可以进行远程呼叫,返回承诺:
angular.module('app.myService', ['app.myOtherService'])
.factory('myService', [
myOtherService,
function(myOtherService) {
function makeRemoteCall() {
return myOtherService.makeRemoteCallReturningPromise();
}
return {
makeRemoteCall: makeRemoteCall
};
}
])
为了对 myService
进行单元测试,我需要模拟 myOtherService
,以便它的 makeRemoteCallReturningPromise
方法返回一个承诺。我是这么做的:
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');
});
}));
正如您从上面可以看到的,我的 mock 的定义取决于 $q
,我必须使用 inject()
加载它。此外,注入模拟应该发生在 module()
,这应该是在 inject()
之前。但是,一旦我更改了模拟的值,它就不会更新。
做这件事的正确方法是什么?