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

时间:2020-08-30 01:28:06

标签: angular jestjs angular-test angular-spectator

我正在尝试测试可修改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。

1 个答案:

答案 0 :(得分:1)

我能够获得拦截方法来采取以下措施。根据需要修改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'来满足接口的要求。