【发布时间】:2021-07-31 09:18:52
【问题描述】:
这个设置非常具体,但我在网上找不到任何类似的资源,所以我在这里发帖以防对任何人有帮助。
关于 Jest 和 Async callback was not invoked 的问题有很多,但我没有发现任何问题的根本问题都围绕着 jest.useFakeTimers() 的使用。使用假计时器时,我的函数应该不会花时间执行,但由于某种原因,Jest 挂起。
我正在使用 Jest 26,因此我手动指定使用 modern 计时器。
这是演示问题的完整代码 sn-p。
jest.useFakeTimers('modern')
let setTimeoutSpy = jest.spyOn(global, 'setTimeout')
async function retryThrowable(
fn,
maxRetries = 5,
currentAttempt = 0
) {
try {
return await fn()
} catch (e) {
if (currentAttempt < maxRetries) {
setTimeout(
() => retryThrowable(fn, maxRetries, currentAttempt + 1),
1 * Math.pow(1, currentAttempt)
)
}
throw e
}
}
describe('retryThrowable', () => {
const fnErr = jest.fn(async () => { throw new Error('err') })
it('retries `maxRetries` times if result is Err', async () => {
jest.clearAllMocks()
const maxRetries = 5
await expect(retryThrowable(() => fnErr(), maxRetries)).rejects.toThrow('err')
for (let _ in Array(maxRetries).fill(0)) {
jest.runAllTimers()
await Promise.resolve() // https://stackoverflow.com/a/52196951/3991555
}
expect(setTimeoutSpy).toHaveBeenCalledTimes(maxRetries)
})
})
完整的错误信息是
Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error: Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.
at mapper (../../node_modules/jest-jasmine2/build/queueRunner.js:27:45)
任何想法将不胜感激
编辑1:我试过--detectOpenHandles,但没有提供新信息
edit 2:我刚刚在一个新项目中尝试了上面的代码 sn-p 并意识到它通过就好了。所以这个问题必须在我的 Jest 配置中的其他地方。当我确定根本原因时,我会回答我自己的问题
【问题讨论】:
标签: javascript asynchronous jestjs