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

75 lines
1.4 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)
window.waitForUpdate = initialCb => {
let end
2016-05-17 06:18:51 +08:00
const queue = initialCb ? [initialCb] : []
function shift () {
const job = queue.shift()
2016-05-19 01:08:14 +08:00
if (queue.length) {
let hasError = false
try {
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 = {
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
},
end: endFn => {
queue.push(endFn)
end = endFn
}
}
return chainer
}
function timeout (n) {
return next => setTimeout(next, n)
}