概述
我在组件的beforeMount 中有个异步请求,在进行单元测试的时候,我需要等这个异步结束后,再进行断言。
先上个代码:
<template>
<div>
<template v-if="lists.length">
<Lists :data="lists" />
</template>
</div>
</template>
<script>
data() {
return {
lists: []
}
},
async beforeMount() {
try {
const res = await axios.get('/url');
this.lists = res.data
} catch (e) {
...
}
}
</scripe>
那么要断言组件Lists
是不是被挂载了,我需要等beforeMount 完成异步请求。
解决方案
1、关于异步,再Vue Test Utils官网中也有相关事例--来自外部的更新,测试时,借用插件flush-promises来等待所有处于 pending 状态或 resolved 状态的 Promise。
那么单元测试可以这么写:
...
import flushPromises from 'flush-promises'
it('base test', async () => {
const wrapper = shallowMount(component)
// 等待所有promises 结束
await flushPromises()
// 断言已经获得到数据
expect(wrapper.vm.$data.lists).toEqual([...])
// 断言子组件`Lists`被渲染
expect(wrapper.findComponent(Lists).exists()).toBeTruthy()
})
这种单元测试比较简单,但是flushPromises 是等待所有pormise,复杂点的,可能影响性能,且需要另外安装flush-promises包。
2、还有另外一种方法,就是借用Reflect.apply()函数,来等待目标beforMount的完成调用。
单元测试可以这么写:
it('base test', async () => {
const wrapper = await shallowMount(component)
// 等待目标异步执行完成
await Reflect.apply(wrapper.vm.$options.beforeMount[0], wrapper.vm, [])
// 等待data 数据改变,此时异步已经完成,但是data中的lists 可能还未发生修改
await wrapper.vm.$nextTick();
// 断言已经获得到数据
expect(wrapper.vm.$data.lists).toEqual([...])
// 断言子组件`Lists`被渲染
expect(wrapper.findComponent(Lists).exists()).toBeTruthy()
})
还有一点需要注意的是,shallowMount 前也需要加上await