[英]Jest: Test for promise that rejects after timeout
我正在嘗試為這個函數的悲傷路徑編寫一個測試:
const awaitFirstStreamForPage = async page => {
try {
await page.waitForSelector('[data-stream="true"]', {
timeout: MAX_DELAY_UNTIL_FIRST_STREAM,
})
} catch (e) {
throw new Error(`no stream found for ${MAX_DELAY_UNTIL_FIRST_STREAM}ms`)
}
}
我設法編寫了一個通過的測試,但運行需要 10 秒,因為它實際上在等待測試完成。
describe('awaitFirstStreamForPage()', () => {
it('given a page and no active stream appearing: should throw', async () => {
jest.setTimeout(15000)
const browser = await puppeteer.launch({ headless: true })
const page = await getPage(browser)
let error
try {
await awaitFirstStreamForPage(page)
} catch (err) {
error = err
}
const actual = error.message
const expected = 'no stream found for 10000ms'
expect(actual).toEqual(expected)
await browser.close()
jest.setTimeout(5000)
})
})
可能有一種方法可以使用 Jest 的假計時器來解決它,但我無法讓它工作。 這是我最好的嘗試:
const flushPromises = () => new Promise(res => process.nextTick(res))
describe('awaitFirstStreamForPage()', () => {
it('given a page and no active stream appearing: should throw', async () => {
jest.useFakeTimers()
const browser = await puppeteer.launch({ headless: true })
const page = await getPage(browser)
let error
try {
awaitFirstStreamForPage(page)
jest.advanceTimersByTime(10000)
await flushPromises()
} catch (err) {
error = err
}
const actual = error.message
const expected = 'no stream found for 10000ms'
expect(actual).toEqual(expected)
await browser.close()
jest.useRealTimers()
})
})
失敗並拋出
(node:9697) UnhandledPromiseRejectionWarning: Error: no stream found for 10000ms
即使我將失敗的函數包裝在try/catch
。 您如何使用假計時器測試這樣的功能?
如果沒有等待,則不可能使用try..catch
從awaitFirstStreamForPage(page)
捕獲拒絕。
的拒絕應被抓到,但打完電話后advanceTimersByTime
后可能flushPromises
。
有可能:
const promise = awaitFirstStreamForPage(page);
promise.catch(() => { /* suppress UnhandledPromiseRejectionWarning */ });
jest.advanceTimersByTime(10000)
await flushPromises();
await expect(promise).rejects.toThrow('no stream found for 10000ms');
問題似乎不是使用假計時器:您期望的錯誤是被拋出的錯誤。 但是,在 Jest 中測試拋出錯誤的函數時,您應該將拋出錯誤的代碼包裝在一個函數中,如下所示:
expect(()=> {/* code that will throw error */}).toThrow()
更多細節在這里: https : //jestjs.io/docs/en/expect#tothrowerror
編輯:對於異步函數,您應該在toThrow
之前使用rejects
; 看這個例子: 你能編寫期望 toThrow 的異步測試嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.