How to change $httpBackend when[method] statements between requests in unit testing?

点点圈 提交于 2019-12-23 16:34:25

问题


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.

回答1:


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



来源:https://stackoverflow.com/questions/25210951/how-to-change-httpbackend-whenmethod-statements-between-requests-in-unit-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!