【问题标题】:Jest check when async function gets called开玩笑检查异步函数何时被调用
【发布时间】:2019-10-04 18:51:04
【问题描述】:

我正在尝试测试是否调用了异步函数(即发即弃)。

Content.js

  export async function fireAndForgetFunction() {
    ...  
  }

  export async function getData() {
    ...
    fireAndForgetFunction()
    return true;
  }

我想测试fireAndForgetFunction 是否被多次调用。

Current test

  import * as ContentFetch from '../Content';

  const { getData } = ContentFetch;
  const { fireAndForgetFunction } = ContentFetch;

  it('test',async () => {
    const spy = jest.spyOn(ContentFetch, 'fireAndForgetFunction');

    await getData();

    expect(spy).toHaveBeenCalled();
  })

测试结果报错说

    Expected number of calls: >= 1
    Received number of calls:    0

我该如何做这个测试?

【问题讨论】:

标签: javascript node.js jestjs


【解决方案1】:

如果您不想在getData() 中等待fireAndForgetFunction,我认为是这种情况,那么在创建间谍时提供fireAndForgetFunction 的模拟实现是您的最佳选择:

it('test', (done) => {
    const spy = jest.spyOn(ContentFetch, 'fireAndForgetFunction')
        .mockImplementation(() => {
          expect(spy).toHaveBeenCalled();
          done();
        })
    getData();
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-01
    • 2021-12-11
    • 2020-10-01
    • 2018-05-22
    • 2020-12-30
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多