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

标签 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));
  }
}

我怎样才能 mock /窥探 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);
  });
});

最佳答案

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

关于jestjs - 如何使用 jest 测试 HttpService.Post 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59860854/

相关文章:

jestjs - 使用 jest.runCLI() 运行单个测试

javascript - 使用 Jest 只运行一次测试

typescript - 为什么 jwtService 未定义?

mongoose - 如何在 Nestjs 中读取 MongooseModule 上的 .env 文件?

node.js - node + ts-jest + ESM,jest.mock 什么都不做

reactjs - 在react-redux-router中测试onEnter

javascript - Nest 无法解析 UserModel 的依赖关系(?)

reactjs - 如何使用 Typescript 将 jest.spyOn 与 React 函数组件一起使用

javascript - jest.mock 不适用于 Javascript 测试和 Typescript 模块

unit-testing - 模拟命名导出以使用 Jest 进行测试