问题
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
betweenit
statements - setting a
.respond(
to afakeResponse
variable. Then changing thefakeResponse
value in eachit
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