在Angular HTTP拦截器中对拦截函数进行单元测试

时间:2020-04-06 10:35:26

标签: angular angular-httpclient angular-httpclient-interceptors

我已经编写了Angular 9 HTTP拦截器,我想以相对隔离的方式对拦截功能进行单元测试。根据我在StackOverflow already上看到的内容,人们建议提出虚假的HTTP请求或return a basic request,因为我使用.pipe方法( TypeError:下一个。 handle(...)。pipe不是函数

这是我的拦截功能,您建议对这个功能进行单元测试吗?

intercept(request: HttpRequest < unknown >, next: HttpHandler): Observable < HttpEvent < unknown >> {
  this.loadingService.show();
  return next.handle(request).pipe(
    catchError((error: HttpErrorResponse) => {
      if (error.status !== 401) {
        this.snackBar.open("There was an error when making your request! " + error.message, 'Okay, I will refresh the page', { duration: 10000 });
      }
      return throwError(error);
    }),
    finalize(
      () => {
        this.loadingService.hide()
      }
    )
  );
}

1 个答案:

答案 0 :(得分:0)

我能够通过在

的“提供者”部分添加以下内容来解决我的问题
TestBed.configureTestingModule

通过提供HTTP_INTERCEPTORSHttpClientTestingModule将使用我制作的拦截器:

{
  provide: HTTP_INTERCEPTORS,
  useClass: LoadingInterceptor,
  multi: true
},