AngularJS corner testing: $ httpBackend.when dynamic answers

I play with AngularJS unit testing when developing a Feed application (RSS). Feed can retrieve remote rss data by analyzing it and storing parsed items. To test the rss request, I use $ httpBackend mock:

beforeEach(inject(function (_$httpBackend_, _feedMock_, _mockConfig_) { _$httpBackend_.when('GET', _mockConfig_.FEED_URL).respond(_feedMock_); })); 

and then below

 $httpBackend.expectGET(mockConfig.FEED_URL); feed.fetch(); $httpBackend.flush(); 

It works great.

But I need Feed to be able to update its state by retrieving updated rss data and adding new elements. So, Feed makes the same request, but receives new updated data. I am trying to recreate the server definition as follows:

 $httpBackend.when('GET', _mockConfig_.FEED_URL).respond(feedMockUpdated); 

and then do the same operation with the wait and flash, but the response is $ httpBackend with the old data (feedMock), not the new one (feedMockUpdated). How can I make $ httpBackend to respond with different data on the same request?

+6
source share
1 answer

You can configure respond with a function, not just a static dataset.

From the docs:

http://docs.angularjs.org/api/ngMock.$httpBackend

response - {function ([status,] data [, headers]) | function (function (method, url, data, headers)} - The response method accepts a set of returned static data or a function that can return an array containing the response status (number), response data (string) and response headers (object).

So, as I understand it in your case, you want the same endpoint to return different data for subsequent calls, you can try something like the following. This is just an implementation of a simple counter that will switch data on a subsequent call.

 var rssCalled = 0; $httpBackend.when('GET', _mockConfig_.FEED_URL).respond(function(method, url, data, headers){ if(rssCalled === 0) { rssCalled++; return [200, feedMock, {}]; } else { return [200, feedMockUpdated, {}]; } }); 
+17
source

Source: https://habr.com/ru/post/943926/


All Articles