我有一个服务函数,它返回一个promise。 当我模拟$ http帖子时,承诺总是会被拒绝状态
beforeEach(inject(function (testService, constantService, $http, $injector, $rootScope, $q) {
$httpBackend = $injector.get("$httpBackend");
_testService_ = testService;
_constantService_ = constantService;
_$rootScope_ = $rootScope;
$scope = $rootScope.$new();
deferred = $q.defer();
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('should post user form data and get an object back', function() {
var response;
var formData = {};
$httpBackend.when("POST", "http://localhost/postform").respond({
data: {
responseStatus:true,
reportPath :"somepath"
}
});
var promise = _testService_.postData("http://localhost" + _constantService_.getWebService('link.dataParameterURL.POST'), formData);
promise.then(function(res) {
response = res;
}, function(errorData){
console.log(errorData)
});
_$rootScope_.$apply();
$httpBackend.flush();
expect(response).toBeDefined();
});
始终未定义响应。
如果我使用以下代码,则承诺得到解决。
var s = $http.post("http://localhost" + constantService.getWebService('link.dataParameterURL.POST'), formData).success(function (res) {
if(res!=undefined && res.responseStatus!=undefined && res.responseStatus === true) {
d.resolve(res);
}else{
d.reject();
}
}).error(function (e,status) {
d.reject(e)
});
s.then(function(res) {
response = res;
}, function(errorData){
console.log(errorData)
});
TestService.js
this.postData = function(url, dataToPOST) {
var d = $q.defer();
$http.post(url, dataToPOST).success(function (res) {
if(res!=undefined && res.responseStatus!=undefined && res.responseStatus === true) {
d.resolve(res);
}else{
d.reject();
}
}).error(function (e,status) {
d.reject(e)
});
return d.promise;
};
答案 0 :(得分:0)
尝试将响应代码添加到您的代码中:
$httpBackend.when("POST", "http://localhost/postform").respond(200, {
data: {
responseStatus:true,
reportPath :"somepath"
}
});