Vue 3 项目配置 Vitest 测试环境需三步:安装 vitest、@vue/test-utils、happy-dom 等依赖;在 vite.config.ts 中配置 test 选项,指定 environment、globals、include 和 coverage;在 package.json 添加 test、test:watch、test:coverage 脚本;最后编写组件测试文件并运行。

Vue 3 项目初始化后配置 Vitest 单元测试环境,核心是三步:装依赖、配环境、加脚本。不需要额外引入 Jest 或复杂工具链,Vitest 与 Vite 天然协同,开箱即用。
安装关键依赖
确保 Node ≥ 18.0.0,然后执行:
-
pnpm add -D vitest @vue/test-utils happy-dom(推荐用
happy-dom替代jsdom,更轻更快,专为 Vue 组件 DOM 测试优化) - 如需覆盖率报告,追加:
pnpm add -D @vitest/coverage-istanbul - 若项目含 JSX/TSX,可选:
pnpm add -D @vitejs/plugin-vue-jsx
配置 Vite 测试选项
在 vite.config.ts 中添加 test 配置块,并在文件顶部加入三斜线引用:
/// <reference types="vitest"></reference>
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [vue()],
test: {
environment: 'happy-dom',
globals: true,
include: ['src/**/*.{test,spec}.{ts,tsx}'],
coverage: {
provider: 'istanbul',
reporter: ['text', 'html'],
lines: 75,
functions: 75
}
}
});
添加运行脚本
在 package.json 的 scripts 中加入:
-
"test": "vitest"—— 一次性运行所有测试 -
"test:watch": "vitest --watch"—— 开发中自动重跑 -
"test:coverage": "vitest run --coverage"—— 生成覆盖率报告
写第一个测试文件
在 src/components/__tests__/Button.test.ts(或 src/components/Button.spec.ts)中写:
import { describe, it, expect } from 'vitest';
import { mount } from '@vue/test-utils';
import Button from '../Button.vue';
describe('Button.vue', () => {
it('renders label correctly', () => {
const wrapper = mount(Button, { props: { label: 'Click me' } });
expect(wrapper.text()).toContain('Click me');
});
it('emits click when clicked', async () => {
const wrapper = mount(Button);
await wrapper.find('button').trigger('click');
expect(wrapper.emitted('click')).toBeTruthy();
});
});
保存后运行 pnpm test,即可看到测试通过结果。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











