Jest Vue:是否可以为快照加载动态导入?



我正在尝试单元测试一个动态加载它的子组件的Vue组件。问题是Jest/Vue utils似乎无法呈现它。有什么办法可以做到吗?

我的组件
<template>
<component :is="component" v-bind="props" />
</template>
<script>
const components = {
dog: () => import('./dog.vue'),
cat: () => import('./cat.vue')
}
export default {
props: { type: String }
computed: {
component() {
return components[this.type]
}
props() { ... }
}
}
</script>

这是我的测试

...
it('renders correctly', async () => {
const wrapper = mount(Component, { ... })
expect(wrapper.element).toMatchSnapshot()
})
...

这是生成的快照文件

// Jest Snapshot v1
exports[`Markdown Token renders correctly 1`] = `<!---->`;

Thanks in advance:)

我不知道为什么它没有在第一个加载周期加载动态组件,但是你可以更新props以确保组件在检查快照之前导入惰性加载的组件。在这些示例中,我试图重置type属性,以便很快导入动态组件。

Vue utils示例

test('render dog component', async () => {
const wrapper = mount(Component, { ... });
// Reset props if you have already passed it as `dog`
await wrapper.setProps({ type: '' });
// Now set it again.
await wrapper.setProps({ type: 'dog' }); 
expect(wrapper.element).toMatchSnapshot()
})

测试库示例:

test('render dog component', async () => {
const { html, updateProps } = render(Component, { ... });
// Reset props if you have already passed it as `dog`
await updateProps({ type: '' });
// Now set it again.
await updateProps({ type: 'dog' }); 
expect(html()).toMatchSnapshot();
})

更新:

最好的方法可能是加载延迟加载组件之前检查快照:

test('render dog component', async () => {
const { html } = render(Component, { ... });
await Promise.all([import('./dog.vue'), import('./cat.vue')]); 
expect(html()).toMatchSnapshot();
})

最新更新