所以我遇到了一个情况,就是我们不得不击中不在我们控制下的“宁静”服务,为了从GET服务中获得json的服务,我们必须通过Content-Type =“application/json”。唯一的问题是Angular从GET请求标题中去除Content-Type。我发现了一个博客帖子上使用$ httpBackend一个装饰,使我们能够拦截呼叫被发送之前,并添加回内容类型建议:
angular
.module('MyApp')
.decorator('$httpBackend', [
'$delegate', function($delegate) {
return function() {
var contentType, headers;
headers = arguments[4];
contentType = headers != null ? headers['X-Force-Content-Type'] : null;
if (contentType != null && headers['Content-Type'] == null)
headers['Content-Type'] = contentType;
return $delegate.apply(null, arguments);
};
}]);
是这样,那精美的作品!现在我们的问题是它打破了我们使用模拟$ httpBackend服务的所有单元测试。我们得到的唯一错误是“未定义”。
Ex。单元测试方法:
it('should return service.model.error if service returns an exception code from EndProject',
inject(function($httpBackend) {
var mockResponse = sinon.stub({ 'exception': 'Unable to retrieve service data' });
$httpBackend.whenPUT(this.endProjectUrl).respond(mockResponse);
var data;
this.service.EndProject().then(function(fetchedData) {
data = fetchedData;
});
$httpBackend.flush();
expect(data.error.state).toBe(true);
expect(data.error.message).toEqual('Unable to retrieve service data');
}));
PhantomJS 2.1.1(Mac OS X的0.0.0)projectService EndProject应该返回service.model.error如果服务返回从EndProject异常代码FAILED 未定义 /用户/ mlm1205 /Documents/THDSource/bolt-projects/html_app/src/app/components/services/project/projectService.spec.js:213:41 invoke @/Users/mlm1205/Documents/THDSource/bolt-projects/html_app/bower_components/angular/angular.js:4560:22 [email protected]/Users/mlm1205/Documents/THDSource/bolt-projects/html_app/bower_components/angular-mocks/angular-mocks.js:2518:26
我试过了,但是这个调用仍然在剥离Content-Type。我有一个拦截器,它注入了我们的负载均衡器所需的另一个头,并且已经尝试过这种Content-Type,但它不起作用。我通过拦截器代码进行调试,并确认它确实添加了标题,但是当您查看“网络”选项卡(Chrome开发工具)中的实际调用时,Content-Type标头消失了。 – Shaggy13spe
我想我以前曾经误解过你的情况。尽管事实上单元测试没有提出真正的请求,但您已经有了适用于您的现有生产装饰器,但在单元测试中失败。我已经更新了答案。看到关于PhantomJS的评论,我很确定错误信息因此被破坏,并且应该说'undefined不是一个函数',因为'$ httpBackend.whenPUT(...)'。 – estus
是的,抱歉,如果我没有更清楚。我会尽量按照你的建议玩一下。我真的想要推回创建该服务的团队来改变它,因为在GET请求上需要该头部是很荒谬的。 – Shaggy13spe