@vue/test-utils 提供了两个主要的挂载方法:mount 和 shallowMount。它们的主要区别在于组件的渲染深度。
mount
完整渲染:
mount会完整地渲染组件,包括其子组件。适用场景:适用于需要测试组件与其子组件之间交互的场景。
示例:
import { mount } from '@vue/test-utils'; import MyComponent from '@/components/MyComponent.vue'; const wrapper = mount(MyComponent);
shallowMount
浅层渲染:
shallowMount只会渲染当前组件,而不会渲染其子组件。子组件会被替换为一个占位符。适用场景:适用于只需要测试当前组件逻辑,而不关心子组件实现的场景。可以提高测试速度和简化测试。
示例:
import { shallowMount } from '@vue/test-utils'; import MyComponent from '@/components/MyComponent.vue'; const wrapper = shallowMount(MyComponent);
选择使用 mount 还是 shallowMount
**使用
mount**:当你需要测试组件与其子组件之间的交互时。**使用
shallowMount**:当你只关心当前组件的逻辑,不关心子组件的实现时。
示例代码
假设我们有一个组件 ParentComponent,它包含一个子组件 ChildComponent。
使用 mount
import { mount } from '@vue/test-utils';
import ParentComponent from '@/components/ParentComponent.vue';
const wrapper = mount(ParentComponent);
// 这里可以测试 ParentComponent 与 ChildComponent 之间的交互使用 shallowMount
import { shallowMount } from '@vue/test-utils';
import ParentComponent from '@/components/ParentComponent.vue';
const wrapper = shallowMount(ParentComponent);
// 这里只测试 ParentComponent 的逻辑,不关心 ChildComponent 的实现选择合适的挂载方法可以帮助你更有效地编写和维护测试用例。
遇到的问题
使用shallowMount 测试的组件中,调用了this.$refs['table'].toggleAllSelection() 方法,报错找不到这个方法,因为这个时候是浅渲染,具体的table并不存在,改用mount问题解决