簡體   English   中英

Jest setTimeout 不暫停測試

[英]Jest setTimeout not pausing test

it('has working hooks', async () => {
  setTimeout(() => {
    console.log("Why don't I run?")
    expect(true).toBe(true)
  }, 15000)

我已經查看了這個答案、Jest 文檔和幾個 GitHub 線程:

禁用 Jest setTimeout 模擬

現在,超時內的函數沒有運行。 如何讓 Jest 暫停執行測試 15 秒,然后運行內部函數?

謝謝!

it('has working hooks', async () => {
  await new Promise(res => setTimeout(() => {
    console.log("Why don't I run?")
    expect(true).toBe(true)
    res()
  }, 15000))
})

或者

it('has working hooks', done => {
  setTimeout(() => {
    console.log("Why don't I run?")
    expect(true).toBe(true)
    done()
  }, 15000)
})

一種很好且干凈的方法(沒有回調),我們可以簡單地運行await並將res傳遞給setTimeout(res, XXX)如下所示:

it('works with await Promise and setTimeout', async () => {
  // await 15000ms before continuing further
  await new Promise(res => setTimeout(res, 15000));

  // run your test
  expect(true).toBe(true)
});

setTimeout 現在可通過 jest 對象使用,它會按您的預期運行: https : //jestjs.io/docs/jest-object#misc

it('works with jest.setTimeout', async () => {
  // pause test example for 15 seconds
  jest.setTimeout(15000)

  // run your test
  expect(true).toBe(true)
});

注意:如果您嘗試在沒有 jest 對象的情況下設置 5000 毫秒或更長時間的超時,jest 會出錯並通知您改用 jest.setTimeout。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM