【发布时间】:2016-04-02 05:11:11
【问题描述】:
我一直在尝试在发送任何请求时测试该过程,并且我想检查标头是否正常。我做错了什么?
检查此代码笔:http://codepen.io/gpincheiraa/pen/qZPrEp
App.js
angular
.module('exampleApp')
.config(configFn);
configFn.$inject = ['$httpProvider'];
function configFn($httpProvider){
$httpProvider.interceptors.push('ApiInterceptors');
}
ApiInterceptors.js
angular
.module('exampleApp')
.factory('ApiInterceptors', factory);
factory.$inject = ['$q'];
function factory($q) {
var service = {
request: handleRequest,
};
return service;
function handleRequest(request){
request.headers['Authorization'] = 'Token token= 59a2cc5ca5fd6c5cb4dadf636d94de1a';
return request;
}
}
ApiInterceptors_spec.js
describe('State check', function(){
var httpBackend;
beforeEach(module('exampleApp'));
beforeEach(inject(eachSpec));
function eachSpec($httpBackend){
httpBackend = $httpBackend;
}
it('Should be have an Authorization header on any request', spec1);
function spec1(){
httpBackend.expectGET('http://www.exampleAPI.com', null, function(headers){
console.log(headers);
expect(headers['Authorization']).toBeDefined();
});
}
});
【问题讨论】:
-
你能在你的 handleRequest 中测试一个 console.log 吗?我认为这不起作用,因为 ApiInterceptor 是在工厂中定义的。在配置阶段不会实例化工厂。我通常在配置阶段转储我的拦截器定义,我不在角度环境中提供它,因为它不是必需的,因为它在其他地方没有用处。
-
@Walfrat 感谢您的建议。我会试试然后告诉你。回答你的问题,不,console.log 永远不会被执行。
标签: angularjs jasmine karma-runner httpbackend angular-mock