如何在AngularJS Jasmine单元测试中模拟返回承诺的服务?
2022-08-30 02:39:22
我有那个用途,它可以发出远程呼叫,返回承诺:myService
myOtherService
angular.module('app.myService', ['app.myOtherService'])
.factory('myService', [
myOtherService,
function(myOtherService) {
function makeRemoteCall() {
return myOtherService.makeRemoteCallReturningPromise();
}
return {
makeRemoteCall: makeRemoteCall
};
}
])
要为 I 进行单元测试,需要 mock ,这样它的方法返回一个 promise。我是这样做的: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');
});
}));
从上面可以看出,我的模拟的定义取决于 ,我必须使用 加载它。此外,注入模拟应该发生在 中,这应该在 前面。但是,一旦我更改了模拟的值,它就不会更新。$q
inject()
module()
inject()
正确的方法是什么?