3

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 !

Stevik
  • 1,092
  • 2
  • 16
  • 37

3 Answers3

2

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.

garkbit
  • 21
  • 2
1

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.

qwetty
  • 1,238
  • 2
  • 10
  • 24
  • In some cases, the decision if a request is made or not is an implementation detail. The test should not assume, what's happning in the implementation – hansmaad Jun 10 '16 at 12:53
1

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);
hansmaad
  • 18,417
  • 9
  • 53
  • 94