【发布时间】:2017-12-21 18:07:27
【问题描述】:
我遇到了一个与使用嵌套承诺进行测试有关的问题。
我在“服务”中有如下方法 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() 或 scope.$apply() 因为这是服务级别。
现在测试用例给出: 从未调用方法 M2 并将 M2 的结果解析为一个承诺对象,而不是实际的响应
仅供参考: 单独对 M2 /M1 进行单元测试,只有一个承诺。
请告诉我如何解决这个问题。
【问题讨论】:
标签: angularjs unit-testing jasmine karma-jasmine