我遇到了与嵌套承诺测试相关的问题。
我在'服务'
中有如下方法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的承诺得到解决,而不是M2(作为其嵌套)任何想法如何也解决嵌套的承诺。
无法使用$ rootscope。$ digest()或范围。$ apply()因为这是服务级别。
目前测试案例给出: 方法M2从未被调用过 并将结果从M2解析为承诺对象,但不是实际响应
仅供参考: 单独对M2 / M1进行的单元测试只有一个承诺。
请告诉我如何解决此问题。
答案 0 :(得分:0)
我现在通过删除下面的承诺嵌套
解决了这个问题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'});
答案 1 :(得分:0)
M(){
M1().then ( function(response1) {
var common;
M2().then( function(response2){
common = response2
// resolve promise1 only if u resolved promise2
deferred1.resolve( do somthing with common and response1)
});
});
};
这是有效解决M2承诺使用的技巧 M2()。然后