Multiple consecutive httpBackend requests trigger an unexpected request

I am testing a sequence that checks a resource until a condition is met.

Book = $resource("/books/:id", {id: "@id"}); function poll(success) { Book.get({id:1}, function() { if (canStop) { success(); } else { $timeout(poll, 1000); } }); }; 

The test below fails with Error: Unsatisfied requests: GET /user_workshops/1

 describe('poll', function() { beforeEach(function() { $httpBackend.expectGET('/books/1').respond(200,{id:1}); $httpBackend.expectGET('/books/1').respond(200,{id:1, newVal:1}); poll(function() { successCalled = true; }); $httpBackend.flush(); $timeout.flush(); canStop=true; $httpBackend.flush(); }); it('should call success when canStop is true', function() { expect(successCalled).toBe(true); }); }); 

I tried rearranging the test order to place the second expectGET just before the second httpBackend.flush() , but then I get:

 Error: Unexpected request: POST /books/1 No more request expected 
+4
source share
2 answers

After an hour of hair pulling, I realized that httpBackend has a very specific order, which checks the called one. The wait should be set not only before you call the flash, but before requesting the resource and when you call the flash, you must make exactly and only the expected requests.

This means that if you want to reset intermediate requests, the order of requests and expectations should be accurate:

 $httpBackend.expectGET('...') resource.get(); $httpBackend.flush() $httpBackend.expectGET('...') resource.get(); $httpBackend.flush() ... etc 

Thus, in the case of the code above, it works if I change the order:

 describe('poll', function() { beforeEach(function() { $httpBackend.expectGET('/books/1').respond(200,{id:1}); poll(function() { successCalled = true; }); $httpBackend.flush(); $httpBackend.expectGET('/books/1').respond(200,{id:1, newVal:1}); $timeout.flush(); canStop=true; $httpBackend.flush(); }); it('should call success when canStop is true', function() { expect(successCalled).toBe(true); }); }); 
+8
source

You can also rebuild the $ httpBackend method for each call. Some kind of:

 var deleteMethod = function () { $httpBackend.when('DELETE', /.*/gi).respond(function(method, url, data) { deleteMethod(); // <--- See here method is rearmed return [200, 'OK', {}]; }); } deleteMethod(); 
0
source

All Articles