How to avoid "Error: unexpected request: GET" every time the AngularJS test executes the function rootScope.digest () or httpBackend.flush ()

All of my UNIT tests, not the E2E tests that run explicit rootScope.digest () or httpBackend.flush () to clear the asynchronous callback, experience an error:

How to avoid the 'Error: Unexpected request: GET' No more request expected 

I believe this is because httpBackend calls the ui-router pattern. I don’t know why he wants it. I do not ask about it. I just want this to trigger my bullied json service.

This error forces me to have the following statement in each it () block:

 $httpBackend.whenGET(/\.html$/).respond(''); 

There should be a more accurate way.

In particular, if the test does not use $ httpBackend in the first place:

  it('should return the list of searched users', function() { // Always use this statement so as to avoid the error from the $http service making a request to the application main page $httpBackend.whenGET(/\.html$/).respond(''); var users = null; UserService.search('TOTO', 1, 10, 'asc', function(data) { users = data.content; }); $rootScope.$digest(); expect(users).toEqual(RESTService.allUsers.content); }); 

The test passes, but it looks like a hacker. Or noobish :-)

EDIT: Another test:

  it('should return the list of users', function () { // Always use this statement so as to avoid the error from the $http service making a request to the application main page $httpBackend.whenGET(/\.html$/).respond(''); // Create a mock request and response $httpBackend.expectGET(ENV.NITRO_PROJECT_REST_URL + '/users/1').respond(mockedUser); // Exercise the service var user = null; RESTService.User.get({userId: 1}).$promise.then(function(data) { user = data; }); // Synchronise $httpBackend.flush(); // Check for the callback data expect(user.firstname).toEqual(mockedUser.firstname); expect(user.lastname).toEqual(mockedUser.lastname); }); 
+5
source share
1 answer

This is obviously by design, your tests should verify that HTTP requests are being executed, and that they are requesting the correct URL. Instead of checking whether /\.html$/ requests were made, why should you instead check to see if requests to endpoints are executed correctly ? Whether it is a partial or API call directive.

If you insist on discarding what might be useful, you can move whenGET() to beforeEach() .

+2
source

All Articles