You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jest使用jest.useFakeTimers时报异步回调5000ms超时问题咨询

该场景非常特殊,我在网上没有找到同类参考资源,因此发布在这里希望能帮到有需要的人。


网上有很多关于Jest报Async callback was not invoked的问题,但我没找到根源和jest.useFakeTimers()相关的案例。理论上使用假定时器时我的函数应该瞬间执行完成,但不知道为什么Jest出现了卡死现象。

我使用的是Jest 26版本,因此手动指定使用modern类型的定时器。

可复现问题的完整代码片段

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()
    }

    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参数运行,但没有输出任何额外的有效信息。


补充2

我刚刚在全新项目中运行了上述代码片段,发现可以正常通过测试。因此问题应该出在我本地的Jest配置上,等我定位到根因会自己更新回答。

内容的提问来源于stack exchange,提问作者Eric Dauenhauer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 05:15:04