如何使用 jest 测试 HttpService.Post 调用

Dev*_*N D 4 jestjs nestjs ts-jest

我正在调用 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));
  }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能嘲笑/窥探 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);
  });
});
Run Code Online (Sandbox Code Playgroud)

小智 13

模拟 http 服务的一个很好的替代方法是在providers 数组中声明它,如下所示。

let httpClient: HttpService;
beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        {
          provide: HttpService,
          useValue: {
            post: jest.fn(() => of({
              // your response body goes here 
            })),
          },
        },
      ],
    }).compile();

    httpClient = module.get<HttpService>(HttpService);
  });
Run Code Online (Sandbox Code Playgroud)

通过在测试模块中提供 HttpService 而不是使用监视,您可以确保 HttpModule 不会被导入或使用,并减少测试代码对其他服务的依赖。


Dev*_*N D 12

使用 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);
      });
  });
});
Run Code Online (Sandbox Code Playgroud)