使用Jest和Spectator测试Angular拦截器的响应

问题描述

我正在尝试测试可修改HTTP请求响应的拦截器。

这是我当前的代码

vars()
到目前为止,我有

及其对应的测试文件

@Injectable()
export class ResponseCamelCaseInterceptor implements HttpInterceptor {
  intercept(
    httpRequest: HttpRequest<Record<string,unkNown>>,httpHandler: HttpHandler,): Observable<HttpEvent<Record<string,unkNown>>> {
    return httpHandler.handle(httpRequest).pipe(
      filter(
        (value): value is HttpResponse<Record<string,unkNown>> =>
          value instanceof HttpResponse,),filter(({ body }) => isPlainObject(body)),map(httpEvent =>
        httpEvent.clone({ body: snaketoCamelCase(httpEvent.body) }),);
  }
}

请注意,我正在使用Angular 10.x.y,Jest 26.x.y和spectator 5.x.y。

解决方法

我能够获得拦截方法来采取以下措施。根据需要修改mockHandler.handle返回。

const mockHandler = {
  handle: jest.fn(() =>  of(new HttpResponse({status: 200,body: {data: 'thisIsWhatImTesting'}})))
};


spectator.service.intercept(new HttpRequest<any>(HttpMethod.GET,'/api'),mockHandler)
      .subscribe((response: HttpResponse<any>) => {
        expect(response.body).toStrictEqual({customKey: '1'});
      });

在订阅lambda中,您需要指定响应作为输入。这应该是拦截器处理后的HttpResponse。

这里的关键是要开玩笑地模拟您需要使用jest.fn()来模拟该函数。为了使TypeScript能够将模拟物识别为正确的类,您需要通过实现'handle'来满足接口的要求。