最佳答案
对这个密码有什么想法吗
jest.useFakeTimers()
it('simpleTimer', async () => {
async function simpleTimer(callback) {
await callback() // LINE-A without await here, test works as expected.
setTimeout(() => {
simpleTimer(callback)
}, 1000)
}
const callback = jest.fn()
await simpleTimer(callback)
jest.advanceTimersByTime(8000)
expect(callback).toHaveBeenCalledTimes(9)
}
```
失败了
Expected mock function to have been called nine times, but it was called two times.
但是,如果我从 LINE-A 中删除 await
,测试就会通过。
承诺和计时器是否不能很好地工作?
我觉得开玩笑的原因可能是等待第二个承诺来解决。