When conducting my testing, I set up the 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 discover 5000 users in channel 12345', function(){
expect( UsersOnlineService.data.usersOnline).toEqual( 50000);
});
In the subsequent test statement, I need the updated value for the channel as everyone has left. This scenario triggers different behavior, so mocking the second request enables me to test that behavior accurately.
However, trying to add $httpBackend.whenGET
in the next it
statement does not replace the original mock value from beforeEach
. It appears to retain the initial 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
});
If attempted without using beforeEach
, both tests fail with the common "unexpectedGet" error message.
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
});
So, how can we effectively modulate mock data between requests?
I also experimented with:
- inserting a
beforeEach
clause betweenit
statements - assigning a
.respond(
to a variable likefakeResponse
, and then adjusting the value offakeResponse
in each followingit
statement.