首页 > 解决方案 > 开玩笑检查异步函数何时被调用

问题描述

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

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

我怎么能做这个测试?

标签: javascriptnode.jsjestjs

解决方案


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

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

推荐阅读