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

我的测试如下:

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

为什么会这样?


当前回答

对于大于27的笑话版本,您可以在规范文件的顶部添加useRealTimers。

下面是代码片段

import { shortProcess, longProcess } from '../../src/index';

jest.useRealTimers();

describe(`something`, function () {
    it('should finish fine', async function () {
        await shortProcess();
        expect(1).toBe(1);
    });

    it('should fail with a timeout', async function () {
        await longProcess();
        expect(1).toBe(1);
    });

    it('should finish fine again', async function () {
        jest.setTimeout(10 * 1000);
        await longProcess();
        expect(1).toBe(1);
    }, 10000);
});

在笑话仓库这里找到github问题。

其他回答

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

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毫秒只是默认设置。

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

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

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

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

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

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

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

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

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

当它是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);
});