我有一个与嵌套 promise 测试相关的问题。
我在“服务”中有如下方法 M
M(){
M1().then (
M2();
return promise1;
)
};
并且 M2 和 M1 具有类似的定义,例如
M2(){
var deferred = $q.defer();
// for M1 u may call someUrl1
$http.get(someUrl2).then(function (success) {
deferred.resolve(success.data);
}, function () {
deferred.reject();
});
return deferred.promise;
}
问题来了: 我有一个测试用例,它执行以下操作
spyOn(Service, 'M2').and.callThrough();
httpBackend.expectGET(SomeUrl1).respond(200,Response1, {'Content-type': 'application/json'});
httpBackend.expectGET(SomeUrl2).respond(200,Response2, {'Content-type': 'application/json'});
Service.M().then(function (Response1) {
expect(Service.M2).toHaveBeenCalled();
// here goes some expect operations on response coming from M()
});
httpBackend.flush();
如上 如果我调用 M() 只有 M1 的 promise 得到解决,而不是 M2(嵌套的)任何想法如何也解决嵌套的 promise 。
不能使用 $rootscope.$digest() 或 scope.$apply() 因为这是在服务级别。
现在测试用例给出: 从未调用过方法 M2 并将 M2 的结果解析为 promise 对象而不是实际响应
仅供引用: 单独对 M2/M1 的单元测试只有一个 promise 。
请告诉我如何解决这个问题。
最佳答案
我现在通过移除下面的 promise 嵌套解决了这个问题
M(){
var common ;
M2().then(function (response2){
common = response2;
});
M1().then (
// use common here
return promise1;
)
};
并在我的测试用例中交换这两个,因为首先解决了 M2
httpBackend.expectGET(SomeUrl2).respond(200,Response2, {'Content-type': 'application/json'});
httpBackend.expectGET(SomeUrl1).respond(200,Response1, {'Content-type': 'application/json'});
关于angularjs - 解决服务 Jasmine 测试中的嵌套 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45140243/