3

In my testing i initiate some model data and mock the response:

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 statement i want the updated value for the channel. Everyone has left, and hypothetically this would trigger other behavior, so i need to mock this second request so i can test that behavioer.

Adding the $httpBackend.whenGET to the next it statment does not override the beforeEach value. It seems to use 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 this without the beforeEach, both fail with the usual "unexpectedGet" 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 mock data between requests?

I also tried:

  • sandwiching a beforeEach between it statements
  • setting a .respond( to a fakeResponse variable. Then changing the fakeResponse value in each it statement.
FlavorScape
  • 13,301
  • 12
  • 75
  • 117
  • I don't see anything that make a http request. You have to setup the `$httpBackend` before the request is made. – runTarm Aug 08 '14 at 19:45

1 Answers1

2

resetExpectations()

Execution

afterEach($httpBackend.resetExpectations);

Documentation

Resets all request expectations, but preserves all backend definitions. Typically, you would call resetExpectations during a multiple-phase test when you want to reuse the same instance of $httpBackend mock.

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

Krzysztof Safjanowski
  • 7,292
  • 3
  • 35
  • 47
  • Ah, I had tried this at some point, then I realized I needed to use expect('GET',regex).respond() isntead of whenGET(...) – FlavorScape Aug 14 '14 at 21:31
  • Actually, i tricked myself into thinking this worked. I'm still not having luck. I made a new question with an example jsFiddle now that I have more knowledge of the problem: http://stackoverflow.com/questions/25370273/how-to-actually-reset-httpbackend-expectations – FlavorScape Aug 18 '14 at 19:13