【问题标题】:AngularJS & Karma-Jasmine - $httpbackend flush only if there is one or more pending requestsAngularJS 和 Karma-Jasmine - 仅当有一个或多个待处理请求时才刷新 $httpbackend
【发布时间】:2015-09-11 13:18:06
【问题描述】:

只有在有一些待处理的请求时才可以调用$httpbackend.flush(); 吗? 所以我永远不会得到

错误:未刷新的请求:1,2,3,...,n

或者

错误:没有待处理的刷新请求!

【问题讨论】:

    标签: javascript angularjs unit-testing karma-jasmine httpbackend


    【解决方案1】:

    根据documentation,您可以使用$http.pendingRequests 属性。像这样的东西会起作用:

    if($http.pendingRequests.length > 0) {
        $httpBackend.flush();
    }
    

    我不确定这是一个非常好的主意,但应该这样做。

    【讨论】:

      【解决方案2】:

      我认为你应该组织你的测试,不要在测试中使用任何“if”。 为什么? 为了简单易懂地了解实际测试的内容,“if”提供了一种在测试失败时通过测试的方法。

      在没有向 API 发出请求时编写单独的测试函数来测试用例。

      阅读 AAA (Arrange Act Assert) 模式在测试中会对您有所帮助。

      【讨论】:

      • 在某些情况下,是否发出请求的决定是实现细节。测试不应该假设,实现中发生了什么
      【解决方案3】:

      如果您不“期望”任何请求,您可以将调用 http.flush(n) 放在 try-catch 块中以忽略异常。

      http.whenGet(/* .. */).respond(/*..*/);  // maybe implementation needs some data
      
      service.doSomething();
      
      try { http.flush(99); }  // resolve all the possible requests my service might have to do
      catch(e) {}
      
      expect(service.isAwesome).toBe(true);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-16
        • 1970-01-01
        • 2019-01-25
        • 2019-01-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多