Nest JS - 为返回Observable Axios Response的函数编写Jest测试用例

问题描述 投票:1回答:1

我是NestJS + Typescript + RxJs技术堆栈的新手。我正在尝试使用Jest为我的一个函数编写单元测试用例,但不确定是否正确执行。

component.service.ts

public fetchComponents(queryParams) {
  const url = this.prepareUrl(queryParams);

  const data$ = this.httpService.get(url);

  return data$
    .pipe(map(({ data }) => data));
}

component.sevice.spec.ts

测试用例工作和通过

describe('fetchComponents', () => {
  const query = {
    limit: 10,
    offset: 0
  };

  const result: AxiosResponse = {
    data: 'Components',
    status: 200,
    statusText: 'OK',
    headers: {},
    config: {}
  };
  it('should return Dummy Data when called successfully', () => {
    componentService.prepareUrl = jest.fn();

    jest.spyOn(httpService, 'get').mockImplementation(() => of(result));

   componentService.fetchComponents(market, query)
    .subscribe(
      (res) => {
        expect(res).toEqual('Components');
      }
    );
  });
});

你能否提供一些关于我应该如何测试这个功能的建议和指示。也没有使用像marbel-rx这样的库我不确定我是否正确测试它。我还应该测试一些其他东西吗?

node.js typescript rxjs jestjs nestjs
1个回答
0
投票

由于Observables是异步的,你必须调用添加异步done参数并在最后执行的done()之后调用expect。否则,jest将在调用subscribe()之后完成测试运行,而不等待执行subscribe的回调的异步执行。试着让你的测试失败,例如期待'Komponents'。测试不会失败。

此外,我建议尽可能使用mockImplementationOnce而不是mockImplementation,以避免在以后的调用中隐式重用模拟行为,从而创建隐式依赖项。

it('should return Dummy Data when called successfully', done => {
// Add done parameter                                   ^^^^
  componentService.prepareUrl = jest.fn();

  jest.spyOn(httpService, 'get').mockImplementationOnce(() => of(result));
// Prefer mockImplementationOnce                   ^^^^

  componentService.fetchComponents(market, query)
    .subscribe(
      (res) => {
        expect(res).toEqual('Components');
        done();
//      ^^^^^^  Call done() when test is finished
      }
    );
});
© www.soinside.com 2019 - 2024. All rights reserved.