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

我的测试如下:

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+,我们只需要在命令行中添加——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)

其他回答

如果有人不解决这个问题,请使用上述方法。我通过用箭头函数包围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);
});

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

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

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

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

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

落下我的2美分在这里,我有同样的问题在dosen的jest单元测试(不是所有的),我注意到,所有开始后,我添加到jestSetup这个polyfill为MutuationObservers:

if (!global.MutationObserver) {
    global.MutationObserver = function MutationObserverFun(callback) {
        this.observe = function(){};
        this.disconnect = function(){};
        this.trigger = (mockedMutationsList) => {
            callback(mockedMutationsList, this);
        };
    };
}

一旦我删除它测试开始工作再次正确。希望能帮助别人。

2022年3月14日,Jest 27.5文档表明了一个新流程:

https://jestjs.io/docs/api#beforeallfn-timeout

在超时前传递第二个参数测试msec的个数。作品!

test('adds 1 + 2 to equal 3', () => {
    expect(3).toBe(3);
},30000);