在 Angular HTTP 拦截器中对拦截功能进行单元测试

Unit testing the intercept function in an Angular HTTP interceptor

我写了一个 Angular 9 HTTP 拦截器,我想在相对隔离的情况下对拦截功能进行单元测试。从我在 Whosebug already, people are suggesting to make fake HTTP requests or return a basic request 上看到的,这对我不起作用,因为我使用 .pipe 方法 (TypeError: next.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()
      }
    )
  );
}

我可以通过在

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

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

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