【发布时间】:2018-03-24 10:44:44
【问题描述】:
我正在尝试理解 Jest 的异步测试。
我的模块有一个函数,它接受一个布尔值并返回一个值的 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 }
我想使用 Jest 对此进行测试。我想我需要使用 Jest 提供的模拟计时器,所以我的测试脚本看起来有点像这样:
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')
})
})
})
无论我是否调用jest.runAllTimers(),我都会收到以下错误/失败的测试
Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
你能解释一下我哪里出错了,我可以做些什么来获得一个通过测试,保证按预期解决?
【问题讨论】:
标签: javascript testing asynchronous jestjs