Vue Test Utils 中如何正确模拟异步组件的加载?
我在用 Vue Test Utils 测试一个动态导入的异步组件,但测试总是报错说组件未定义。试过用 flushPromises 也没搞定,是不是哪里写错了?
组件是这样导入的:
const AsyncComp = defineAsyncComponent(() => import('@/components/MyAsync.vue'))
测试代码里我这样写:
test('renders async component', async () => {
const wrapper = mount(ParentComponent)
await flushPromises()
expect(wrapper.findComponent({ name: 'MyAsync' }).exists()).toBe(true)
})
defineComponent包装一下父组件,而且flushPromises要放在正确的位置。我当时的血泪教训是直接用
mount挂载包含异步组件的父组件,结果死活等不到组件加载。后来发现得这么写:另外,如果你直接用组件名查找,记得检查大小写是否一致,我在这也栽过跟头。Vue3的异步组件测试确实比Vue2麻烦不少。