How can I change $ httpBackend when [method] between requests in unit testing?

In my testing, I initiate some model data and mock the answer:

beforeEach(function(){
   var re = new RegExp(/^http\:\/\/.+?\/users-online\/(.+)$/);
   $httpBackend.whenGET(re).respond({id:12345, usersOnline:5000});
});      

it('should find 5000 users in channel 12345', function(){
    expect( UsersOnlineService.data.usersOnline).toEqual( 50000);
});

      

then say in the next test expression, I want an updated value for the channel. Everyone is gone and hypothetically this will cause different behavior, so I need to mock this second request so that I can test this behavior.

Adding $httpBackend.whenGET

to the next it

status does not override the value beforeEach

. It seems to be using the original mock value:

it('should find 0 users in channel 12345', function(){
    $httpBackend.whenGET(re).respond({id:12345, usersOnline:0});
    expect( UsersOnlineService.data.usersOnline).toEqual( 50000); //fails
});

      

And if I do it like I did before, they each fail with the usual "unexpected" error.

it('should find 5000 users in channel 12345', function(){
     var re = new RegExp(/^http\:\/\/.+?\/users-online\/(.+)$/);
     $httpBackend.whenGET(re).respond({id:12345, usersOnline:5000});
    expect( UsersOnlineService.data.usersOnline).toEqual( 50000); //fails
});

it('should find 0 users in channel 12345', function(){
      var re = new RegExp(/^http\:\/\/.+?\/users-online\/(.+)$/);
     $httpBackend.whenGET(re).respond({id:12345, usersOnline:0});
    expect( UsersOnlineService.data.usersOnline).toEqual( 0); //fails
});

      

How to modulate data layout between requests?

I've also tried:

  • sandwich a beforeEach

    between operatorsit

  • setting a variable .respond(

    to a variable fakeResponse

    . Then change the value fakeResponse

    in each expression it

    .
+3


source to share


1 answer


resetExpectations ()

Execution

afterEach($httpBackend.resetExpectations);

      



Documentation

Drops all pending requests, but retains all underlying definitions. Typically, you will call resetExpectations during a multiphase test when you want to reuse the same $ httpBackend mock instance.

documentation source: https://docs.angularjs.org/api/ngMock/service/ $ httpBackend

+2


source







All Articles