【问题标题】:How to test HttpService.Post calls using jest如何使用 jest 测试 HttpService.Post 调用
【发布时间】:2020-05-08 16:19:23
【问题描述】:

我正在调用 Nestjs 服务中的 API,如下所示,

import { HttpService, Post } from '@nestjs/common';

export class MyService {

constructor(private httpClient: HttpService) {}

public myMethod(input: any) {
    return this.httpClient
      .post<any>(
        this.someUrl,
        this.createObject(input.code),
        { headers: this.createHeader() },
      )
      .pipe(map(response => response.data));
  }
}

我如何模拟/监视对 this.httpClient.post() 的调用以在不触及实际 API 的情况下返回响应?

describe('myMethod', () => {
    it('should return the value', async () => {
      const input = {
        code: 'value',
      };
      const result = ['test'];

      // spyOn?

      expect(await myService.myMethod(input)).toBe(result);
  });
});

【问题讨论】:

    标签: jestjs nestjs ts-jest


    【解决方案1】:

    使用 spyOn 让它工作。

    describe('myMethod', () => {
        it('should return the value', async () => {
          const input = {
            code: 'mock value',
          };
    
          const data = ['test'];
    
          const response: AxiosResponse<any> = {
            data,
            headers: {},
            config: { url: 'http://localhost:3000/mockUrl' },
            status: 200,
            statusText: 'OK',
          };
    
          jest
            .spyOn(httpService, 'post')
            .mockImplementationOnce(() => of(response));
    
          myService.myMethod(input).subscribe(res => {
            expect(res).toEqual(data);
          });
      });
    });
    

    【讨论】:

    • 谢谢!不要忘记按照stackoverflow.com/a/55212136/5869296 中的说明调用 done()
    • 这只有在 httpService 被暴露 /public 时才有效,而在大多数情况下它不应该如此。最好直接使用模拟对象或笑话自动模拟功能来模拟它。
    猜你喜欢
    • 2019-12-28
    • 2018-09-28
    • 2019-04-21
    • 2019-05-16
    • 2020-01-24
    • 2016-01-19
    • 2022-01-24
    • 2020-06-25
    • 2019-04-11
    相关资源
    最近更新 更多