Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid the 'Error: Unexpected request: GET' every time an AngularJS test does a rootScope.digest() or httpBackend.flush()

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

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

I reckon it is because httpBackend calls the ui-router template. I don't know why it wants to do so. I'm not asking for this. I only want it to call my mocked json service.

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

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

There must be a neater way.

Specially if the test has no use of the $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 hackish. 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);
  });
like image 324
Stephane Avatar asked Oct 31 '22 06:10

Stephane


1 Answers

This is obviously by design, your tests should be checking that HTTP calls are being made and that they're requesting the correct URL. Instead of checking whether requests are made to /\.html$/ why not instead check whether requests are made to the correct endpoints? Whether that be a directives partial or an API call.

If you insist on throwing away what could be a useful test, you could move your whenGET() to a beforeEach().

like image 170
juco Avatar answered Nov 15 '22 06:11

juco