React / 系统课时
配置 Vitest 测试环境
配置 Vitest 测试环境
本课为 React 18 与 Vite 项目接入 Vitest,配置 jsdom、Testing Library 和全局初始化文件,并编写一个可运行的组件测试。完成后,你可以使用监听模式快速开发,也能在持续集成中执行一次性测试。
学习目标
- 安装 Vitest、
jsdom与 React Testing Library - 配置测试环境、初始化文件和测试脚本
- 编写并运行一个包含用户交互的组件测试
前置检查与依赖安装
Vitest 4 需要 Node.js 20 或更高版本,并与 Vite 6 或更高版本配合。先确认当前项目运行时,避免安装成功后因版本不兼容而无法启动。:contentReference[oaicite:4]{index=4}
node --version
npm --version预期输出:
v20.<MINOR>.<PATCH>
<NPM_VERSION><MINOR>、<PATCH> 和 <NPM_VERSION> 取决于本机环境。然后在现有 React 18 + Vite 项目中安装测试依赖:
npm install -D vitest jsdom @testing-library/react @testing-library/jest-dom @testing-library/user-event预期结果:
added <COUNT> packages<COUNT> 会随项目已有依赖变化。Vitest 默认使用 Node 环境;组件测试需要 DOM API,因此本课改用 jsdom。:contentReference[oaicite:5]{index=5}
配置测试环境
在项目根目录修改 vite.config.ts。从 vitest/config 导入 defineConfig 后,可以在现有 Vite 配置中直接添加 test 字段。:contentReference[oaicite:6]{index=6}
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vitest/config';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
globals: true,
setupFiles: './src/test/setup.ts',
include: ['src/**/*.{test,spec}.{ts,tsx}'],
css: true,
},
});这份配置会让测试获得 document、window 等浏览器式 API,扫描 src 下以 .test 或 .spec 命名的 TypeScript 文件,并在每个测试文件执行前加载初始化脚本。
创建 src/test/setup.ts:
import '@testing-library/jest-dom/vitest';该导入会注册 toBeInTheDocument、toHaveTextContent 等 DOM 断言。setupFiles 会在测试文件之前运行,适合放置断言扩展、统一清理或稳定的测试替身。:contentReference[oaicite:7]{index=7}
组织测试文件
小型项目可以把测试放在组件旁边,便于同步修改;跨组件测试、公共测试工具和全局初始化文件则放在 src/test。本课采用以下结构:
src/
├─ components/
│ ├─ Counter.tsx
│ └─ Counter.test.tsx
└─ test/
└─ setup.ts
vite.config.ts
package.json这不是唯一目录规则,关键是命名稳定、职责清楚,并与 include 的匹配范围一致。
编写第一个组件测试
创建 src/components/Counter.tsx:
import { useState } from 'react';
export function Counter() {
const [count, setCount] = useState(0);
return (
<section>
<p aria-live="polite">Count: {count}</p>
<button type="button" onClick={() => setCount((value) => value + 1)}>
Increment
</button>
</section>
);
}创建 src/components/Counter.test.tsx:
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it } from 'vitest';
import { Counter } from './Counter';
describe('Counter', () => {
it('increments after the user clicks the button', async () => {
const user = userEvent.setup();
render(<Counter />);
// 先验证初始界面,再通过真实点击路径触发状态更新。
expect(screen.getByText('Count: 0')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Increment' }));
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});
});测试通过角色和可见文本查找元素,关注用户能观察到的行为,而不是组件内部的 useState 实现。这使重构内部代码时,测试仍能保留业务价值。
添加命令并运行测试
在 package.json 的 scripts 中加入以下片段;这是配置片段示例,应与现有脚本合并,不要覆盖项目中的其他命令。
{
"scripts": {
"test": "vitest",
"test:run": "vitest run"
}
}开发时运行监听模式:
npm test预期结果:
DEV v<VERSION> <PATH>
✓ src/components/Counter.test.tsx (1 test) <TIME>
Test Files 1 passed (1)
Tests 1 passed (1)持续集成或提交前检查使用一次性模式:
npm run test:run预期输出:
RUN v<VERSION> <PATH>
✓ src/components/Counter.test.tsx (1 test) <TIME>
Test Files 1 passed (1)
Tests 1 passed (1)
Duration <TIME><VERSION>、<PATH> 与 <TIME> 是动态值,不同 Vitest 版本的空格和附加统计行可能略有差异,但测试文件数和测试数都应为 1 且状态为通过。
典型失败处理
出现 document is not defined,通常说明测试仍在默认 Node 环境中。检查 environment: 'jsdom' 是否位于生效的配置文件内,并确认运行命令所在目录就是项目根目录。
出现 Invalid Chai property: toBeInTheDocument,说明 @testing-library/jest-dom/vitest 没有被加载。检查 setupFiles 路径、文件扩展名和安装依赖是否正确。
出现测试文件未被发现,先核对文件名是否匹配 .test.tsx 或 .spec.tsx,再检查 include。不要为了让测试被发现而把扫描范围扩大到 node_modules 或构建目录。