你能告诉我如何测试Angular 4提供的HttpInterceptor。我已经根据示例创建了一个拦截器,但不知道如何测试它。下面是我的拦截器,我想测试自定义头文件是否被添加,当响应状态是401 window.location.href完成。单元测试来自Angular 4的HttpInterceptor
export class MyInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const headers = new HttpHeaders();
this.addHeader(headers); // This will add headers
const changedReq = req.clone({ headers: headers });
return next.handle(req)
.catch(err => {
if (err instanceof HttpErrorResponse) {
switch (err.status) {
case 302:
case 401:
window.location.href = "http//google.com";
break;
default:
throw new Error(this.getErrorMessage(err));
}
}
return Observable.throw(err);
});
}
谢谢,但我不明白你在这种情况下你的模型。我想做一个http.get调用,并且想要检查拦截器是否添加了头部并且想要模拟响应。 – Angad
你可以跳过。如果你不嘲笑任何东西,它不是必需的。 –