angularjs - 解决服务 Jasmine 测试中的嵌套 promise

标签 angularjs unit-testing jasmine karma-jasmine

我有一个与嵌套 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/

相关文章:

javascript - Angularjs - 使用 php 上传文件

javascript - Angular Js : get $localStorage value in view page

php - Laravel 4 测试 "Command"s?

unit-testing - 如何在 Golang 中模拟结构方法

Angular 2 rc5,服务单元测试问题

angularjs - 如何在 jasmine 中测试被拒绝的 Angular (1.6.1) promise ?

javascript - 如何动态禁用 Angular 指令?

AngularJs 使用 $scope 变量作为 URL 嵌入 MS Word 文档

c# - 使用 XUnit 测试动态扩展

angularjs - Karma错误无法调用未定义的方法 'module'