vue2/test/helpers/wait-for-update.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

82 lines
1.5 KiB
TypeScript
Raw Normal View History

import Vue from 'vue'
// helper for async assertions.
// Use like this:
//
// vm.a = 123
// waitForUpdate(() => {
// expect(vm.$el.textContent).toBe('123')
// vm.a = 234
// })
// .then(() => {
// // more assertions...
// })
2016-05-19 01:08:14 +08:00
// .then(done)
2022-05-20 08:22:26 +08:00
interface Job extends Function {
wait?: boolean
fail?: (e: any) => void
}
2022-05-23 15:15:29 +08:00
const waitForUpdate = (initialCb: Job) => {
let end
2022-05-20 08:22:26 +08:00
const queue: Job[] = initialCb ? [initialCb] : []
2022-05-20 08:22:26 +08:00
function shift() {
const job = queue.shift()
2016-05-19 01:08:14 +08:00
if (queue.length) {
let hasError = false
try {
2022-05-20 08:22:26 +08:00
job!.wait ? job!(shift) : job!()
2016-05-19 01:08:14 +08:00
} catch (e) {
hasError = true
const done = queue[queue.length - 1]
if (done && done.fail) {
done.fail(e)
}
}
if (!hasError && !job!.wait) {
2016-05-19 01:08:14 +08:00
if (queue.length) {
Vue.nextTick(shift)
}
}
} else if (job && (job.fail || job === end)) {
2016-05-19 01:08:14 +08:00
job() // done
}
}
2016-05-19 01:08:14 +08:00
Vue.nextTick(() => {
if (!queue.length || (!end && !queue[queue.length - 1]!.fail)) {
2016-11-25 00:50:20 +08:00
throw new Error('waitForUpdate chain is missing .then(done)')
2016-05-19 01:08:14 +08:00
}
shift()
})
const chainer = {
2022-05-20 08:22:26 +08:00
then: nextCb => {
queue.push(nextCb)
return chainer
2016-06-01 07:09:57 +08:00
},
thenWaitFor: wait => {
if (typeof wait === 'number') {
wait = timeout(wait)
}
2016-06-01 07:09:57 +08:00
wait.wait = true
queue.push(wait)
return chainer
},
2022-05-20 08:22:26 +08:00
end: endFn => {
queue.push(endFn)
end = endFn
}
}
return chainer
}
2022-05-20 08:22:26 +08:00
function timeout(n) {
return next => setTimeout(next, n)
}
2022-05-23 15:15:29 +08:00
export { waitForUpdate }