AngularJS & Karma-Jasmine - flash $ httpbackend only if there are one or more pending requests
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.
source to share
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.
source to share
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);
source to share