如果我有一些代码导致某些事情发生异步但不是导致做某事的根本原因(不能等待回调),那么在循环中发生的事情(即测试自动保存)将如何最好的方式来做它。
这是一个失败的测试示例,大致是我想要实现的目标。
function myProgram(something, onEvent) {
something().then(() => onEvent());
}
test('Promise test', () => {
const onEvent = jest.fn();
expect(onEvent).not.toBeCalled();
const doSomething = () => Promise.resolve();
myProgram(doSomething, onEvent);
expect(onEvent).toBeCalled(); // Expected mock function to have been called.
})
答案 0 :(得分:0)
您要么从测试中返回承诺
test('Promise test', () => {
const onEvent = jest.fn();
expect(onEvent).not.toBeCalled();
const doSomething = () => Promise.resolve();
myProgram(doSomething, onEvent);
expect(onEvent).toBeCalled(); // Expected mock function to have been
called.
return doSomething
})
或使用async/await
test('Promise test', async() => {
const onEvent = jest.fn();
expect(onEvent).not.toBeCalled();
const doSomething = await () => Promise.resolve();
myProgram(doSomething, onEvent);
expect(onEvent).toBeCalled(); // Expected mock function to have been called.
})
另请查看docs