Javascript 调用异步函数时的Jest检查
我试图测试是否调用了异步函数(fire和forget)Javascript 调用异步函数时的Jest检查,javascript,node.js,jestjs,Javascript,Node.js,Jestjs,我试图测试是否调用了异步函数(fire和forget) Content.js export async function fireAndForgetFunction() { ... } export async function getData() { ... fireAndForgetFunction() return true; } 我想测试是否多次调用了fireAndForgetFunction 当前测试 import * as
Content.js
export async function fireAndForgetFunction() {
...
}
export async function getData() {
...
fireAndForgetFunction()
return true;
}
我想测试是否多次调用了fireAndForgetFunction
当前测试
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
如何进行此测试?如果您不想等待
getData()
中的fireandfegetfunction
,我假设是这样,那么在创建间谍时提供fireandfegetfunction
的模拟实现是您的最佳选择:
it('test', (done) => {
const spy = jest.spyOn(ContentFetch, 'fireAndForgetFunction')
.mockImplementation(() => {
expect(spy).toHaveBeenCalled();
done();
})
getData();
})
可能重复的