4

我正在尝试测试一个修改来自 HTTP 请求的响应的拦截器。

这是我当前的代码:

@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) }),
      ),
    );
  }
}

及其对应的测试文件我到目前为止:

describe(ResponseCamelCaseInterceptor.name, () => {
  const createService = createServiceFactory(ResponseCamelCaseInterceptor);

  test('some description', () => {
    const { service } = createService();
    const fakeHttpRequest = new HttpRequest('POST', 'https://...', { custom_key: '1' });

    service.intercept(fakeHttpRequest, 'what should I put here for HttpHandler?').subscribe(() => {
      // expect(httpResponse.body).toStrictEqual({ customKey: '1' });
    });
  });
});

请注意,我使用的是 Angular 10.xy、Jest 26.xy 和 Spectator 5.xy

4

1 回答 1

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 将模拟识别为正确的类,您需要通过实现“句柄”来满足接口。

于 2020-08-31T14:16:32.833 回答