我无法使用MockBackend检查我的代码在单元测试中发送的标头。
我正在测试中执行以下操作:
injectAsync([Http, XHRBackend], (http: Http, backend: MockBackend) => {
return new Promise((pass, fail) => {
var request: Request;
backend.connections.subscribe((c: MockConnection) => {
request = c.request;
c.mockRespond(new Response(new ResponseOptions()));
})
let req_headers = new Headers({'Authorization': 'Bearer foo'});
http.get('/', new ResponseOptions({headers: req_headers})).subscribe(
() => {
// I try to get the request headers here
console.log(request.headers);
pass();
},
fail
)
})
})
然而,当我尝试回读标题时,我得到一个空标题集。 log语句的结果为我提供了Headers{_headersMap: Map{}}
。
我错过了什么?
答案 0 :(得分:3)
事实上,他们在那里但是header属性是Map
所以你需要这样做:
// All headers
for (var key of connection.request.headers.keys()) {
console.log('- key = ' + key);
}
// Authorization header
var auth = connection.request.headers.get('Authorization');
console.log('auth = '+auth);
答案 1 :(得分:1)
请看这个插件(文件src / myservice.spec.ts第52-71行);
it('should do something',injectAsync([Http, XHRBackend], (http: Http, backend: MockBackend) => {
return new Promise((pass, fail) => {
backend.connections.subscribe((c: MockConnection) => {
console.log(c.request.headers);// headers will be defined here
//if you want this to pass, you have to do a little bit more with the response
c.mockRespond(new Response(new ResponseOptions()));
})
//headers will need to be imported from 'angular2/http'
let req_headers = new Headers({'Authorization': 'Bearer foo'});
//response options is not what you need to pass into http.get. you want to pass RequestOptions
http.get('/', {headers: req_headers}).subscribe(
() => {
pass();
},
//fail needs to be called to fail.
fail();
)
})
}));