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

我的测试如下:

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无关。我的一个方法调用是在本地运行时获得一个空对象和一个空异常。一旦我添加了一个空检查,失败的测试和控制台日志就消失了。

if(response !== null){
    this.searchSubj.next(resp);
 }
 else {
    return;
 }

其他回答

随着Jest的发展,这个问题的答案也发生了变化。当前答案(2019年3月):

您可以通过向it添加第三个参数来覆盖任何单个测试的超时。也就是说,它('运行缓慢',()=>{…}, 9999) 您可以使用jest.setTimeout更改默认值。这样做: / /配置 "setupFilesAfterEnv":[//不是setupFiles . ”。/ src /嘲笑/ defaultTimeout.js” ], 而且 //文件:src/jest/defaultTimeout.js /*全局笑话*/ jest.setTimeout (1000) 就像其他人注意到的那样(与此没有直接关系),对于async/await方法来说,done是不必要的。

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

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

默认的超时时间是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)也会抛出相同的错误。

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

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

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