Reputation: 33
I am doing unit testing on my AngularJS app using their setup with jasmine and karma. I have been using AngularJS mock $httpbackend
:
https://docs.angularjs.org/api/ngMock/service/$httpBackend
The problem I have is testing the following module:
define([
'angular',
'app',
'angularRoute',
], function (angular, app) {
'use strict';
app.config(function ( $httpProvider) {
/* Angular automatically adds this header to the request,
preventing us from being able to make requests to the server on another port */
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}).factory('equipmentService', ['$http', '$rootScope', function($http, $rootScope) {
var factory = {
setEquipmentState: function(state){
this.equipmentState = state.state;
console.log('equipment state', this.equipmentState);
redirectState(this.equipmentState);
}
}
var redirectState = function (state) {
switch(state) {
case 'Active':
$location.path('/active');
break;
case 'Review':
$location.path('/review');
break;
default:
// don't change views
}
}
function stateCheck () {
$http.get($rootScope.backendServer+'/equipment/state/changed')
.then(function (data) {
factory.setEquipmentState(data.data);
})
.then(stateCheck);
}
stateCheck();
return factory;
}]);
});
I always have a pending http request to the server; as soon as the server responds, send another http request. Because of this, even if my mock httpbackend is expecting the request, once it responds, I don't know how to avoid the error:
Error: Unexpected request: GET url
No more request expected
Is there a way for me to ignore this error for this particular request? Or a way for the mock httpbackend to expect infinite requests to that url?
Upvotes: 1
Views: 991
Reputation: 1716
You should use a combination of $httpBackend.expect
and $httpBackend.when
to cover a required call that can happen multiple times:
$httpBackend.expectPUT('URI')... (makes it required) $httpBackend.whenPUT('URI')... (allows for multiple calls)
Upvotes: 0
Reputation: 39522
One should use the $httpBackend.when
suite of methods when your tests are expecting more than one request to the same URL.
https://docs.angularjs.org/api/ngMock/service/$httpBackend
Upvotes: 2