首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Jest和Spectator测试角拦截器的响应

用Jest和Spectator测试角拦截器的响应
EN

Stack Overflow用户
提问于 2020-08-30 01:28:06
回答 1查看 1.1K关注 0票数 4

我正在尝试测试一个从HTTP请求修改响应的Interceptor。

以下是我的当前代码:

代码语言:javascript
复制
@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) }),
      ),
    );
  }
}

到目前为止,我有相应的测试文件:

代码语言:javascript
复制
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' });
    });
  });
});

请注意,我使用的是角10.x.y、Jest26.x.y和Spectator 5.x.y。

EN

回答 1

Stack Overflow用户

发布于 2020-08-31 14:16:32

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

代码语言:javascript
复制
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‘来满足接口。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63653206

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档