【发布时间】:2016-07-08 12:17:51
【问题描述】:
这是我的代码:
export class httpService {
constructor($q, $http){
this.$q = $q;
this.$http = $http;
}
static getError(response) {
if (response.data && response.data.messages) {
return response.data.messages;
} else {
return ["Sorry, there is an internal issue..."];
}
}
httpRequest(url, method, data) {
url = encodeURI(url);
var deferred = this.$q.defer();
this.$http({
method: method,
url: url,
data: data
}).then(function (response) {
deferred.resolve(response.data);
}, function (response) {
deferred.reject(httpService.getError(response));
});
return deferred.promise;
}
}
我的测试代码:
import angular from 'angular';
import ngMock from 'angular-mocks';
import {httpService as HttpService} from '../http.service';
describe("httpService", ()=>{
var httpService;
var $q;
var $timeout;
var $httpBackend;
var campaignHttpRequestHandler;
var campaignTestUrl = 'api/campaign/aGJhZ2ZmZ2RmcmZ0';
var campaignData = {
"articles": [
{
"id": "1207",
"type": "a",
"order": 1
},
{
"id": "940",
"type": "p",
"order": 2
},
{
"id": "1268",
"type": "a",
"order": 3
},
{
"id": "954",
"type": "p",
"order": 4
}
],
"year_month": "201606",
};
beforeEach(inject((_$q_, _$timeout_, _$httpBackend_)=>{
$q = _$q_;
$timeout = _$timeout_;
$httpBackend = _$httpBackend_;
campaignHttpRequestHandler = $httpBackend.when('Get', campaignTestUrl).respond(campaignData);
}));
beforeEach(()=>{
httpService = new HttpService($q, $httpBackend);
});
afterEach(function () {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
describe("#httpRequest()", ()=>{
it('should get campaign data', ()=>{
$httpBackend.expect('Get', campaignTestUrl);
httpService.httpRequest(campaignTestUrl, 'Get').then(
(response)=>{
expect(response).toEqual(campaignData);
}
);
$httpBackend.flush();
});
});
});
错误:
#httpRequest()
✖ should get campaign data
Chrome 51.0.2704 (Mac OS X 10.11.5)
Error: Unexpected request: [object Object] undefined
并且我调试到源代码中,$http 已经被替换为 $httpBackend。 不知何故,$httpBackend 的第一个参数:method,它是一个包含方法、url、数据的对象,与$http 中的请求参数相同。显然,这是错误的。但是不知道怎么解决~
请帮忙。 卡在这里一整天了~
【问题讨论】:
-
当您使用 'GET' 而不是 'Get' 时会发生什么?甚至更好:whenGET() 和 expectGET()?
-
@JBNizet 同样的错误,并没有解决问题
-
$http 不等于 $httpBackend,它们不能互换使用。如果按照建议的方式测试服务,就不会发生这种错误。手动实例化
HttpService类是否有原因? -
$httpBackend 是 $http 的模型。我想测试这个服务,所以我需要使用 $httpBackend 来模拟 $http。 @estus
-
$httpBackend是$http的后端。$httpdepends on it。你不能通过它而不是$http。顺便说一句,你已经得到了正确的答案。
标签: angularjs unit-testing angular-mock