【问题标题】:Solve Nested Promise in a Service Jasmine Test解决服务茉莉花测试中的嵌套承诺
【发布时间】: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


    【解决方案1】:

    我现在已经通过删除下面的承诺嵌套解决了这个问题

    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'});
    

    【讨论】:

    【解决方案2】:
    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().then

    【讨论】:

      猜你喜欢
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 2021-05-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多