AngularJS & Karma-Jasmine - $httpbackend flush only if there is one or more pending requests

843 views Asked by At

Is it possible to call $httpbackend.flush(); only if there are some pending request ? So I will never get

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

Or

Error: No pending request to flush !

3

There are 3 answers

0
garkbit On

According to the documentation there's an $http.pendingRequests property you could use. Something like this would work:

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

I'm not sure it s a terribly good idea, but that should do it.

1
qwetty On

I think You should organize your tests to not use any "if" inside test. Why? To keep it simple and easy to understand what is actually tested, "if" gives a way to pass test while it should fail.

Write separate test function to test case when no request are made to API.

Read about AAA (Arrange Act Assert) pattern in testing it will helps you.

0
hansmaad On

If you do not "expect" any requests you could put the call to http.flush(n) in a try-catch block in ignore 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);