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

时间:2020-01-22 13:28:16

标签: jestjs nestjs ts-jest

我正在下面的nestjs服务中调用API,

<meta charset="...">

我如何才能开玩笑/间谍监视对this.httpClient.post()的调用以返回响应而不会触及实际的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));
  }
}

1 个答案:

答案 0 :(得分:5)

使用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);
      });
  });
});