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

我的测试如下:

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 我是否得到这个错误似乎是随机的

为什么会这样?


当前回答

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);

其他回答

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

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

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

事实证明,如果您的expect断言是错误的,它有时会吐出超过超时的错误消息。

我能够通过在promise回调中放入console.log()语句来解决这个问题,并看到console.log()语句在jest输出中运行。一旦我修复了expect断言,超时错误就消失了,测试可以正常工作。

我花了很长时间才弄明白,希望这能帮助需要阅读这篇文章的人。

还有另一个解决方案:在Jest配置文件中设置超时,例如:

{ // ... other stuff here
    "testTimeout": 90000
}

如果有人不解决这个问题,请使用上述方法。我通过用箭头函数包围async func来修正我的错误。如:

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);
});
// In jest.setup.js
jest.setTimeout(30000)

如果在Jest <= 23:

// In jest.config.js
module.exports = {
  setupTestFrameworkScriptFile: './jest.setup.js'
}

如果在笑话> 23:

// In jest.config.js
module.exports = {
  setupFilesAfterEnv: ['./jest.setup.js']
}