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

zfycwa2u  于 2022-12-30  发布在  TypeScript
关注(0)|答案(3)|浏览(156)

我正在调用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));
  }
}

如何在jest中模拟/spyOn对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);
  });
});
0sgqnhkj

0sgqnhkj1#

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

2fjabf4q2#

模拟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);
  });

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

mo49yndu

mo49yndu3#

我有一个方法使用了我的模拟post调用的结果,所以我得到了这个结果

describe('my test', function () {
  let service: LegalTextAdminClientFactory;

  const httpService = {
    get: jest.fn(),
    post: jest.fn().mockImplementation(() => of({ data: {} })),
  };
  const configService = {
    get: jest.fn().mockReturnValue('mock'),
  };

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        { provide: HttpService, useValue: httpService },
        { provide: ConfigService, useValue: configService },
        LegalTextAdminClientFactory,
      ],
    }).compile();

    service = await module.get(LegalTextAdminClientFactory);
  });
});

所以通过返回这个“of()”,你甚至可以用管道传输它的结果

相关问题