有人可以告诉我如何测试Angular提供的Http拦截器。据我所知,我已经创建了一个拦截器,但不确定如何对其进行测试。下面是我的拦截器,我在下面的Interceptor测试用例中写到,但得到了异常
有人可以建议我吗?
@Injectable()
export class AutherizationInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.headers.has(InterceptorSkipHeader)) {
const headers = req.headers.delete(InterceptorSkipHeader);
return next.handle(req.clone({ headers }));
} else {
const modified = req.clone({
setHeaders:
{
'Authorization': localStorage.getItem(GlobalVariables.AUTHERIZATION_TOEKN),
'Content-Type': 'application/json'
}
});
return next.handle(modified);
}
}
}
describe('Lang-interceptor.service', () => {
beforeEach(() => TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: AutherizationInterceptor,
multi: true
}]
}));
it('adds Authorization header', inject([HttpClient, HttpTestingController], (http: HttpClient, httpMock: HttpTestingController) => {
http.post(`${environment.baseUrl}api/potential/search`,null).subscribe(
response => {
expect(response).toBeTruthy();
}
);
const req = httpMock.expectOne(r =>
r.headers.has('Authorization'));
expect(req.request.method).toEqual('POST');
const headers = new HttpHeaders().set(InterceptorSkipHeader, '')
req.flush(headers);
httpMock.verify();
}));
});
Lang-interceptor.service adds Authorization header
TypeError: Cannot read property 'length' of null
TypeError: Cannot read property 'length' of null
at HttpHeaders.push../node_modules/@angular/common/fesm5/http.js.HttpHeaders.applyUpdate (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/common/fesm5/http.js:200:1)
at http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/common/fesm5/http.js:171:60