Vue组件单元测试核心是用Vue Test Utils搭配Jest,通过mount或shallowMount渲染组件,验证输入输出逻辑、事件响应、DOM表现和生命周期行为。

在 Vue 组件中写单元测试,核心是用 Vue Test Utils(VUT)搭配 Jest(或其他测试运行器),模拟组件渲染、触发交互、断言行为与状态。关键不在于“测所有”,而在于验证组件的**输入输出逻辑、事件响应、DOM 表现和生命周期行为**是否符合预期。
用 mount 或 shallowMount 渲染组件
Vue Test Utils 提供两个主要挂载方法:
- mount:完整挂载,包含所有子组件(适合集成测试或需真实子组件行为的场景)
- shallowMount:只挂载当前组件,自动 stub 子组件(推荐用于大多数单元测试,避免干扰、提升速度)
例如测试一个带按钮和计数器的组件:
```js// Counter.vue
<template>
<div>
<span>{{ count }}</span>
<button @click="increment">+1</button>
</div>
</template>
<script>
export default {
data() {
return { count: 0 };
},
methods: {
increment() { this.count++ }
}
};
</script>
``````js
// Counter.spec.js
import { shallowMount } from '@vue/test-utils';
import Counter from './Counter.vue';
describe('Counter.vue', () => {
it('starts with count 0', () => {
const wrapper = shallowMount(Counter);
expect(wrapper.vm.count).toBe(0);
});
it('increments count when button is clicked', () => {
const wrapper = shallowMount(Counter);
wrapper.find('button').trigger('click');
expect(wrapper.vm.count).toBe(1);
});
});
```
测试 props、emits 和响应式数据
组件常依赖外部输入(props)和向外通信(emits),测试时需显式传入并监听:
立即学习“Java免费学习笔记(深入)”;
- 通过
props选项传入初始 prop 值 - 用
emitted()检查组件是否正确触发事件 - 对
computed或watch的行为,直接读取值或观察副作用
it('emits "update" when incrementing', () => {
const wrapper = shallowMount(Counter, {
props: { initial: 5 } // 假设组件支持 initial prop
});
wrapper.vm.increment();
expect(wrapper.emitted()).toHaveProperty('update');
expect(wrapper.emitted('update')[0]).toEqual([6]);
});
```
处理异步操作与生命周期
若组件在 mounted 中发起请求或使用 nextTick,测试需等待异步完成:
- 用
await wrapper.vm.$nextTick()等待 DOM 更新 - 对 Promise 异步逻辑(如 API 调用),可 mock
fetch或使用jest.mock - 避免在测试中依赖真实网络;用
mockResolvedValue控制返回结果
快照测试与 DOM 断言结合使用
快照(expect(wrapper.html()).toMatchSnapshot())适合捕获模板结构变化,但不宜替代逻辑断言。更推荐:
- 用
wrapper.text()或wrapper.find('span').text()断言内容 - 用
wrapper.contains('button')或findComponent验证元素存在 - 对 v-if/v-show,检查
exists()或isVisible()


















