我試圖瞭解Jest的異步測試。使用setTimeout測試Promise
我的模塊有一個函數,它接受一個布爾值並返回一個值的Promise。執行器函數調用setTimeout
,並且在超時回調中,promise根據最初提供的布爾值來解析或拒絕。代碼如下所示:
const withPromises = (passes) => new Promise((resolve, reject) => {
const act =() => {
console.log(`in the timout callback, passed ${passes}`)
if(passes) resolve('something')
else reject(new Error('nothing'))
}
console.log('in the promise definition')
setTimeout(act, 50)
})
export default { withPromises }
我想測試這個使用玩笑。我想我需要使用模擬定時器玩笑提供,所以我的測試腳本看起來有點像這樣:
import { withPromises } from './request_something'
jest.useFakeTimers()
describe('using a promise and mock timers',() => {
afterAll(() => {
jest.runAllTimers()
})
test('gets a value, if conditions favor',() => {
expect.assertions(1)
return withPromises(true)
.then(resolved => {
expect(resolved).toBe('something')
})
})
})
我碰到下面的錯誤/失敗測試,是否我叫
Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
您能否解釋我要出錯的地方,以及我可能做些什麼來獲得通過測試,以便按照預期的方式解決問題?
This Works!非常感謝解釋和解釋和代碼示例。 –