你能告訴我如何測試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
你可以跳過。如果你不嘲笑任何東西,它不是必需的。 –