超出 Jest Call 重试次数

Ham*_*shi 10 javascript unit-testing jestjs babeljs

我在以下测试中出错。我的节点版本是:v12.10.0。有没有 setTimeout 的替代方案?

   test('demo code', async () => {
        const cc = await projectSetup(project);
        const onNotification = jest.fn();
        cc.sendNotification();
        await waitForExpect(() => {
            expect(onNotification).toHaveBeenCalledTimes(2);
        });

    });
Run Code Online (Sandbox Code Playgroud)

错误日志是

Call retries were exceeded

  at ChildProcessWorker.initialize (../../../node_modules/jest-worker/build/workers/ChildProcessWorker.js:230:21)
Run Code Online (Sandbox Code Playgroud)

Rid*_*ola 13

jest.useFakeTimers();只需在导入后添加

...
jest.useFakeTimers();

test('demo code', async () => {
        const cc = await projectSetup(project);
        const onNotification = jest.fn();
        cc.sendNotification();
        await waitForExpect(() => {
            expect(onNotification).toHaveBeenCalledTimes(2);
        });

    });
Run Code Online (Sandbox Code Playgroud)

它在我的代码中有效

  • 您还可以在“jest.config.js”设置文件中添加“jest.useFakeTimers()”,如果您已将项目设置为使用它,则无需在每个文件的导入之后添加它。这对我有用。 (2认同)

小智 10

就我而言,实际问题在于承诺处理。当我开玩笑地一次性运行所有测试用例时,我遇到了同样的问题。

解决方案: 尝试单独运行一项测试,然后查看出现什么错误。

在单独运行一个有问题的测试后,我得到了以下错误,之前我得到的是Call retries were exceeded

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "TypeError: Cannot read property 'code' of undefined".] {
  code: 'ERR_UNHANDLED_REJECTION'
}
Run Code Online (Sandbox Code Playgroud)

有了这个,我确信问题出在 catch 块上,当我将它添加到异步服务 API 函数中时,测试用例工作得非常好。也许您也可以尝试同样的方法,看看它是否适合您。

我正在使用以下配置:

节点: 15.13.0

npm: 7.8.0

笑话: 26.6.3

  • 单独运行失败的测试确实揭示了实际的错误!谢谢! (2认同)