javascript - 开玩笑检查异步函数何时被调用
问题描述
我正在尝试测试是否调用了异步函数(即发即弃)。
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
我怎么能做这个测试?
解决方案
如果您不想等待fireAndForgetFunction
in (我认为是这种情况),那么在创建间谍时getData()
提供模拟实现是您的最佳选择:fireAndForgetFunction
it('test', (done) => {
const spy = jest.spyOn(ContentFetch, 'fireAndForgetFunction')
.mockImplementation(() => {
expect(spy).toHaveBeenCalled();
done();
})
getData();
})
推荐阅读
- javascript - 阅读 elem.style - 规范保证结果格式吗?
- ios - URLQuery item does not grab the location coordinate
- r - 在 R 错误中运行卡方:“x”的所有条目必须是非负且有限的
- javascript - Return specific number of with array data
- c# - 精灵和脚本中的四元数问题
- sed - why the ending g keyword in this sed substitute command is not matching all the occurrences?
- reactjs - 当我在使用 Reach-Router(或我的顶级路由)的索引路由时,如何有条件地渲染组件?
- javascript - 图表数据未显示在画布中,但 console.log 显示了预期值
- javascript - jQuery sortable not working when dragging into parent div if empty
- mysql - 基于日期范围连接两个数据表作为 MySQL 中的唯一标准