Ensuring $httpBackend flush for series of requests

1.2k views Asked by At

I have a need to test an in-house angular service implemented under Angular 1.5.9 with jasmine/karma.

I need to write a test which checks that the response of a particular service function is as expected. To do this I am constructing a mock object, instantiating the service, calling the function to be tested and using expect().toBe() to check the returned value.

Unfortunately, the service makes numerous calls to it's own functions, many of which make further calls using the $http angular service. It does this in order to populate objects such as user data, locale and other bespoke product information. Suffice to say that I am not in a position to refactor the service into a better architecture; I must simply construct this test.

As there are so many calls to $http I intend to mock all the data it would request using a series of lines such as this:

var mockGetCartData = { "d": null, "message": null }; // at the top of the describe
$httpBackend.when('GET', /(.*)\/order\/api\/v1\/GetCart/).respond(200, mockGetCartData); // in the beforeEach

When I call the function to be tested I am immediately calling $httpBackend.flush() but, as the test is failing, I am concerned that what I need to do is cause each (faked) $http call to be flushed before the next is made.

Do I need to do this or is setting up all of the $httpBackend.when().respond() entries, acting on the test function and then calling a single flush() enough? If this is not enough, what should I do?

2

There are 2 answers

0
Michael Nelson On BEST ANSWER

You do not need to call flush() for each request that is made as it flushes all pending requests.

See the Documentation: https://docs.angularjs.org/api/ngMock/service/$httpBackend

or source: https://github.com/angular/angular.js/blob/master/src/ngMock/angular-mocks.js#L1830

However, if the $http requests in the method under test are chained together (so subsequent requests are only made after the previous request is resolved) then you will need to flush() for every request in the chain. Without seeing the code under test that's all the help I am able to give.

0
Ankit Shah On

You have to mock the only required http call in It block and flush it after the function call. Otherwise it will try to flush unexpected http calls which will result in error.