我刚接触单元测试并尝试运行测试用例,但始终收到错误Unexpected request POST service
以下是我的代码
角度服务
angular
.module('testModule')
.factory('testService', testService)
testService.$inject = ['$q', '$http'];
function testService($q, $http){
return {
getAll: function(obj){
let config = {
headers : {
'Content-Type':'application/x-www-form-urlencoded'
}
};
let deferred = $q.defer();
let payload = 'keyQueryParam=' + obj
$http.post('url', payload, config.headers).then(response => {
deferred.resolve(response.contents)
})
return deferred.promise;
}
}
}
单元测试
describe('Test Service', function(){
let mockTestFactory, httpBackend;
beforeEach(function(){
angular.mock.module('testModule');
});
beforeEach(inject(function($httpBackend, _testService_){
httpBackend = $httpBackend;
mockTestFactory= _testService_;
}));
it('Return a POST response from a Service function', function(){
var url = "http://localhost:3000/";
var obj = ['ret-2','ret-5','ret-6'];
let payload = 'keyQueryParam=' + obj
let config = {
headers : {
'Content-Type':'application/x-www-form-urlencoded'
}
};
httpBackend
.when('POST','url', payload, function(config.headers) {
expect(config.headers['Content-Type']).toBe('application/x-www-form-urlencoded');
return config.headers['Content-Type'] === 'application/x-www-form-urlencoded';
})
.respond(200, { status : "success"});
mockTestFactory.getAll(obj).then(function(response) {
console.log(response);
});
httpBackend.flush();
expect(true).toBe(true);
});
});
提前致谢
答案 0 :(得分:0)
如果您的电话是POST,请使用201状态代码,如下所示
httpBackend
.when('POST', 'url', payload, function(config.headers) {
expect(config.headers['Content-Type']).toBe('application/x-www-form-urlencoded');
return config.headers['Content-Type'] === 'application/x-www-form-urlencoded';
})
.respond(201, {
status: "success"
});
现在尝试它应该运行。