AngularJS & Karma-Jasmine - flash $ httpbackend only if there are one or more pending requests

Can it be called $httpbackend.flush();

only if there is a pending request? So I will never get

Error: unblocked requests: 1,2,3, ..., n

or

Error: No pending reset request!

+3


source to share


3 answers


According to the documentation, there is a property $http.pendingRequests

that you could use. Something like this will work:

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

      



I'm not sure if this is an awfully good idea, but this should do it.

+2


source


I think you should organize your tests so that you don't use any "if" test inside. What for? To keep things simple and easy to understand, what is actually tested is the "if" makes it possible to pass the test until it works.

Write a separate test function to test for the case when the API is not receiving a request.



Read about the AAA (Arrange Act Assert) pattern when testing, it will help you.

+1


source


If you are not expecting any requests, you can place the call http.flush(n)

in a try-catch block, ignoring the exception.

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

      

+1


source







All Articles