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

我的测试如下:

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

其他回答

此处指定的超时时间必须小于默认超时时间。

默认的超时时间是5000,框架默认为jasmine。您可以通过添加在测试中指定超时

jest.setTimeout(30000);

但这是针对测试的。或者,您可以为框架设置配置文件。

配置是

// jest.config.js
module.exports = {
  // setupTestFrameworkScriptFile has been deprecated in
  // favor of setupFilesAfterEnv in jest 24
  setupFilesAfterEnv: ['./jest.setup.js']
}

// jest.setup.js
jest.setTimeout(30000)

请参见这些线程:

5055号考试第七次出局

茉莉花。DEFAULT_TIMEOUT_INTERVAL可配置#652

注:拼写错误的setupFilesAfterEnv(即setupFileAfterEnv)也会抛出相同的错误。

对于Jest 24.9+,我们只需要在命令行中添加——testTimeout:

--testTimeout= 10000 // Timeout of 10 seconds

缺省超时值为5000 (5000 ms - 5秒)。这将适用于所有测试用例。

或者如果您只想给特定的函数超时,那么您可以在声明测试用例时使用此语法。

test(name, fn, timeout)

例子

test('example', async () => {

}, 10000); // Timeout of 10 seconds (default is 5000 ms)

将此添加到您的测试中,无需过多解释

beforeEach(() => {
  jest.useFakeTimers()
  jest.setTimeout(100000)
})

afterEach(() => {
  jest.clearAllTimers()
})

在我的例子中,这个错误开始随机出现,即使在设置超时30000之后也不会消失。只需在终端中结束进程并重新运行测试,就可以为我解决这个问题。我还删除了超时,测试仍然再次通过。

当它是async from test时,它应该调用async/await。

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