我正在使用他们的设置与茉莉和业力在我的AngularJS应用程序上进行单元测试 . 我一直在使用AngularJS mock $httpbackend
:
https://docs.angularjs.org/api/ngMock/service/$httpBackend
我遇到的问题是测试以下模块:
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;
}]);
});
我总是有一个挂起的http请求到服务器;一旦服务器响应,发送另一个http请求 . 因此,即使我的模拟httpbackend期待请求,一旦它响应,我不知道如何避免错误:
错误:意外请求:GET url不再需要请求
有没有办法让我忽略这个特定请求的错误?或者模拟httpbackend的方式是期望对该URL的无限请求?
2 回答
当您的测试期望对同一URL的多个请求时,应该使用
$httpBackend.when
方法套件 .https://docs.angularjs.org/api/ngMock/service/$httpBackend
您应该使用
$httpBackend.expect
和$httpBackend.when
的组合来覆盖可能多次发生的所需呼叫:$ httpBackend.expectPUT('URI')...(使其成为必需)$ httpBackend.whenPUT('URI')...(允许多个调用)