如何增加笑话中的测试超时值?

Rya*_*yan 40 javascript jestjs playwright

我想验证一个可以在一分钟后更新的函数,并且我在代码中设置了一些睡眠,但我的默认超时值是 15000 毫秒,我的代码有睡眠 60000 毫秒,所以它返回此错误:

thrown: "Exceeded timeout of 15000 ms for a test.
    Use jest.setTimeout(newTimeout) to increase the timeout value,
    if this is a long-running test."
Run Code Online (Sandbox Code Playgroud)

我的代码在这里:

it('shows that timeline can get updated after one minute', async () => {
    await selectTimeForTimeLine.selectTime('Last 5 minutes');
    await page.waitForTimeout(3000);
    const defaultTime = await alarmTimeLine.xAxisValues();
    await page.evaluate(() => {
      return new Promise((resolve) => setTimeout(resolve, 60000));
    });
    const correntTime = await alarmTimeLine.xAxisValues();
    expect(defaultTime).not.toEqual(correntTime);
  });
Run Code Online (Sandbox Code Playgroud)

我应该放在哪里jest.setTimeOut()?我想将超出的超时值增加到 70000 毫秒,以确保我的代码运行良好。

Rya*_*yan 94

要设置单个测试的超时,请将第三个选项传递给it/test,例如:

 it('testing balabala', async () => {
   ...
 }, 70000);
Run Code Online (Sandbox Code Playgroud)

该值以毫秒为单位。在本例中为 70 秒。


mik*_*ana 15

来自jest.setTimeout() 文档

设置测试和钩子之前/之后的默认超时间隔(以毫秒为单位)。这仅影响调用该函数的测试文件。

即 jest.setTimeout()在文件级别处理。他们的示例并没有说清楚,但您应该jest.setTimeout()在测试文件的顶部运行:

const SECONDS = 1000;
jest.setTimeout(70 * SECONDS)

describe(`something`, () => {
  it('works', async () => {
    asset(true).isTruthy()
  });
})
Run Code Online (Sandbox Code Playgroud)

更新:我现在已向 Jest 团队发送了一份 PR,该 PR 已被接受,以澄清文档。他们现在读到:

要在同一文件中的不同测试上设置超时间隔,请对每个单独的测试使用超时选项。

这是 Jest 29.5 及更高版本的一部分。


LeO*_* Li 8

升级到 v28+ 后,这jest.setTimeout()对我来说不再起作用了。我必须在以下位置明确设置超时./jest.config.js

// jest.config.js
module.exports = {
    // ...
    testTimeout: 70000
}
Run Code Online (Sandbox Code Playgroud)