用悬念测试Vue3异步设置组件的正确方法是什么? [英] What is the proper way to test Vue3 async setup component with suspense?
问题描述
毫无疑问,Suspense功能可以使代码库更简洁,但是尽管整洁,却很难进行测试.具体来说,目前还没有很好的记录.
No doubt that Suspense feature leads to a cleaner code base, but as tidy as it is, it turns to be hard to test. Specifically it is not well documented yet.
VUE CLI生成的常规应用
Regular app generated by VUE CLI
- 技术堆栈:Vuex,路由器,PWA,开玩笑的单元测试
我按照以下建议使用了Suspense组件:
I made use of Suspense component as recommended as follows:
<RouterView name="default" v-slot="{ Component, route }">
<transition :name="route.meta.transition" mode="out-in" :duration="300" :key="route.path">
<Suspense >
<template #default>
<component :is="Component" :key="route.path"/>
</template>
<template #fallback>
<div class="top-0 right-0 h-screen w-screen z-50 flex justify-center items-center">
<div class="animate-spin rounded-full h-32 w-32 border-t-2 border-b-2 border-yellow-700"></div>
</div>
</template>
</Suspense>
</transition>
</RouterView>
我的路线和风景都很少:
- 其中一个用于登录视图
// here is the gotcha, if ever I removed async from setup the test runs well otherwise it always returns empty vm.
async setup(){
const router = useRouter()
const route = useRoute()
const form = reactive(new Form({
username:'',
password:'',
}))
}
我的测试套件如下:
test('Shows login form', async () => {
let wrapper = mount(Login,{
// tried set global.stubs.transition to false
renderDefaultSlot: true // tried as well to move this attr to beforeEach hook
})
expect(wrapper.exists()).toBe(true) // passes
await nextTick()
// tried to flushPromises()
console.log(wrapper.vm) // always empty object {}
expect(wrapper.findAll('div')).toBeTruthy() // fails accordingly as it can't run helper methods to get the parentElement
})
这里的任何VUE老手都可以给出提示或解决方法!
在Github上进行的所有公开讨论表明,我不是唯一在这个问题上迷迷糊糊的人,但是现在这只是一场讨论.
Does any VUE veteran here can give a hint or workaround!
All open discussions on Github shows that I am not the only one stumbled on this issue, but for now it is just a discussion.
https://github.com/vuejs/vue-test-utils-next/issues/108#issue-611802592
https://github.com/vuejs/vue-test-utils/issues/956
推荐答案
经调查后,上面的Github讨论中引用了一个小助手:
After investigation wrote a little helper quoted from Github discussion above:
import {defineComponent,h,Suspense } from 'vue'
import { mount } from '@vue/test-utils'
import flushPromises from 'flush-promises';
const mountSuspense = async (component, options) => {
const wrapper = mount(defineComponent({
render() {
return h(Suspense, null, {
default: h(component),
fallback: h('div', 'fallback')
})
}}),options)
await flushPromises()
return wrapper
}
describe('App renderes', ()=>{
test('About page renders',async()=>{
const wrapper = await mountSuspense(About)
await console.log(wrapper.text()) // it works
})
})
这篇关于用悬念测试Vue3异步设置组件的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!