在 Jest 结合 Vue Test Utils 进行组件测试时,`shallowMount` 是一个常用的方法,用于创建组件的**浅渲染实例**
在 Jest 结合 Vue Test Utils 进行组件测试时,shallowMount 是一个常用的方法,用于创建组件的浅渲染实例。它的核心特点是不会递归渲染子组件,只会将子组件渲染为占位符(如 <ChildComponent />),从而专注于测试当前组件本身的逻辑,避免子组件的行为干扰测试结果。
基本用法
import { shallowMount } from '@vue/test-utils';
import MyComponent from '@/components/MyComponent.vue';describe('MyComponent', () => {it('renders correctly', () => {// 浅渲染组件const wrapper = shallowMount(MyComponent, {propsData: { // 传递 propsmsg: 'Hello'},mocks: { // 模拟全局对象(如 $store、$router)$store: {state: { count: 0 }}}});// 断言组件内容expect(wrapper.text()).toContain('Hello');});
});
与 mount 的区别
shallowMount:只渲染当前组件,子组件以占位符形式存在,适合隔离测试当前组件。mount:递归渲染所有子组件,适合测试组件间交互(如父子组件通信)。
常用配置选项
propsData:传递组件的 props。mocks:模拟全局属性或方法(如$t、$router.push)。stubs:手动指定需要 stub 的组件(即使是当前组件的子组件,也可强制 stub)。data:覆盖组件的初始 data。methods:覆盖组件的方法(用于模拟或劫持方法)。
注意事项
-
子组件隔离:由于不渲染真实子组件,若测试逻辑依赖子组件的行为(如事件触发),需手动 stub 子组件的方法或事件。
const wrapper = shallowMount(MyComponent, {stubs: {ChildComponent: {template: '<div @click="handleClick" />',methods: { handleClick: jest.fn() }}} }); -
样式与 DOM 结构:浅渲染可能无法完全反映真实 DOM 结构(如子组件的 HTML),若需测试完整渲染结果,应使用
mount。 -
Vue 3 兼容性:在 Vue 3 中,
shallowMount已整合到@vue/test-utilsv2+ 中,用法与 Vue 2 类似,但需注意部分 API 差异(如props替代propsData)。
shallowMount 是组件单元测试的利器,尤其适合验证组件自身的渲染逻辑、props 接收、事件触发等核心功能,推荐优先使用以提高测试效率和隔离性。
