我在用木偶师和小丑做一些前端测试。

我的测试如下:

describe("Profile Tab Exists and Clickable: /settings/user", () => {
    test(`Assert that you can click the profile tab`, async () => {
      await page.waitForSelector(PROFILE.TAB);
      await page.click(PROFILE.TAB);
    }, 30000);
});

有时,当我运行测试时,一切都按预期工作。其他时候,我得到一个错误:

Timeout -在jest.setTimeout指定的5000毫秒超时时间内没有调用异步回调。 在node_modules/jest-jasmine2/build/queue_runner.js:68:21 <br/> 在超时。callback [as _onTimeout] (node_modules/jsdom/lib/jsdom/browser/Window.js:633:19)

这很奇怪,因为:

我将超时时间指定为30000 我是否得到这个错误似乎是随机的

为什么会这样?


当前回答

这是一个相对较新的更新,但它更直接。如果你使用的是Jest 24.9.0或更高版本,你可以在配置中添加testTimeout:

// in jest.config.js
module.exports = {
  testTimeout: 30000
}

其他回答

你也可以得到基于愚蠢的拼写错误的超时错误。例如,这个看似无伤大雅的错误:

describe('Something', () => {
  it('Should do something', () => {
    expect(1).toEqual(1)
  })

  it('Should do nothing', something_that_does_not_exist => {
    expect(1).toEqual(1)
  })
})

产生以下错误:

FAIL src/TestNothing.spec.js (5.427s)
  ● Something › Should do nothing

    Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.
      
      at node_modules/jest-jasmine2/build/queue_runner.js:68:21
      at Timeout.callback [as _onTimeout] (node_modules/jsdom/lib/jsdom/browser/Window.js:678:19)

虽然所发布的代码示例没有受到这种影响,但它可能是其他地方失败的原因。还要注意,我没有为任何地方设置超时——无论是在这里还是在配置中。5000毫秒只是默认设置。

确保调用done();在回调中,或者它不能通过测试。

beforeAll((done /* Call it or remove it */ ) => {
  done(); // Calling it
});

它适用于所有具有done()回调的其他函数。

Test接受一个超时参数。见https://jestjs.io/docs/api # testname-fn-timeout。下面是一个例子:

async function wait(millis) {
  console.log(`sleeping for ${millis} milliseconds`);
  await new Promise(r => setTimeout(r, millis));
  console.log("woke up");
}
test('function', async () => {
  await wait(5000);
}, 70000);

当网络很慢或使用await进行许多网络调用时,就会出现超时问题。这些场景超过了缺省超时时间,即5000毫秒。要避免超时错误,只需增加支持超时的全局变量的超时。全局变量及其签名的列表可以在这里找到。

对于 是 24.9

我想补充(这是一个有点长的评论),即使超时3000,我的测试有时仍然会(随机)失败

Timeout -在jest.setTimeout指定的5000ms超时内没有调用异步回调。

感谢Tarun的精彩回答,我认为修复大量测试的最短方法是:

describe('Puppeteer tests', () => {
  beforeEach(() => {
    jest.setTimeout(10000);
  });

  test('Best Jest test fest', async () => {
    // Blah
  });
});