【发布时间】:2016-10-07 07:55:30
【问题描述】:
所以我遇到了这样一种情况,我们不得不访问一个不受我们控制的“restful”服务,为了在 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 服务的所有单元测试。我们得到的唯一错误是“未定义”。
例如。单元测试方法:
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) 如果服务从 EndProject FAILED 返回异常代码,则 projectService EndProject 应返回 service.model.error 不明确的 /Users/mlm1205/Documents/THDSource/bolt-projects/html_app/src/app/components/services/project/projectService.spec.js:213:41 调用@/Users/mlm1205/Documents/THDSource/bolt-projects/html_app/bower_components/angular/angular.js:4560:22 workFn@/Users/mlm1205/Documents/THDSource/bolt-projects/html_app/bower_components/angular-mocks/angular-mocks.js:2518:26
【问题讨论】:
标签: angularjs unit-testing jasmine httpbackend