动态import带来的问题
如果你在使用Vue的时候同时使用了动态加载,比如有两个组件Parent和Child。Parent会动态加载Child。
Parent组件内容
<template>
<div>
Parent
<Child />
</div>
</template>
<script>
export default {
components: {
Child: () => import('./Child')
}
}
</script>
Child组件内容
<template>
<div>我是子组件</div>
</template>
如果你使用shallowMount
const wrapper = shallowMount(Parent)
你可能会得到这样的错误信息
[Vue warn]: Failed to resolve async component
解决方案
未来shallowMount一定会解决这个问题的。不过,我们可以使用以下方案暂时解决这个问题。
把shallowMount换成mount,然后手动stub用动态加载导入的子组件
const wrapper = mount(Parent, {
stubs: {
Child: true
}
})
Child会被加载成<child-stub>,就像我们使用shallowMount一样。