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

57 lines
1.0 KiB
JavaScript
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 => {
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()
} catch (e) {
hasError = true
const done = queue[queue.length - 1]
if (done && done.fail) {
done.fail(e)
}
}
2016-05-19 01:08:14 +08:00
if (!hasError) {
if (queue.length) {
Vue.nextTick(shift)
}
}
2016-05-19 01:08:14 +08:00
} else if (job && job.fail) {
job() // done
}
}
2016-05-19 01:08:14 +08:00
Vue.nextTick(() => {
if (!queue.length || !queue[queue.length - 1].fail) {
console.warn('waitForUpdate chain is missing .then(done)')
}
shift()
})
const chainer = {
then: nextCb => {
queue.push(nextCb)
return chainer
}
}
return chainer
}