Vite + React + Vitest:一个你可以在10分钟内复制的简单测试设置
发布: (2026年2月25日 GMT+8 17:30)
3 分钟阅读
原文: Dev.to
Source: Dev.to
Introduction
如果你使用 Vite + React + TypeScript,添加测试的最快方式是 Vitest。
在本文中,我将展示一个可以直接复制的简洁配置。
Why this stack?
- Vite – 快速的开发服务器
- Vitest – 感觉像 Jest 的测试运行器,但在 Vite 项目中更快
- React Testing Library – 从用户的角度进行测试
此配置在 pnpm 和中小型前端应用中表现良好。
1) Install packages
pnpm add -D vitest jsdom @testing-library/react @testing-library/jest-dom @testing-library/user-event
2) Update vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
setupFiles: './src/test/setup.ts',
globals: true,
},
})
What this does
jsdom提供类似浏览器的环境。setupFiles在测试运行前执行一次。globals: true让你可以直接使用describe、it、expect,无需每次导入。
3) Create src/test/setup.ts
import '@testing-library/jest-dom'
这会添加诸如 toBeInTheDocument() 的辅助函数。
4) Add scripts to package.json
{
"scripts": {
"test": "vitest run",
"test:watch": "vitest",
"test:ui": "vitest --ui"
}
}
Usage
pnpm test– 运行一次测试(CI)。pnpm test:watch– 在编码时以监听模式运行测试。
5) Example component test
Component: src/components/Counter.tsx
import { useState } from 'react'
export function Counter() {
const [count, setCount] = useState(0)
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount((c) => c + 1)}>Increment</button>
</div>
)
}
Test: src/components/Counter.test.tsx
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Counter } from './Counter'
describe('Counter', () => {
it('increments count when button is clicked', async () => {
render(<Counter />)
await userEvent.click(screen.getByRole('button', { name: /increment/i }))
expect(screen.getByText('Count: 1')).toBeInTheDocument()
})
})
此测试检查真实行为,而不是内部状态细节。
Common beginner mistakes
- 为 React 测试使用 node 环境(应使用
jsdom)。 - 忘记设置
@testing-library/jest-dom。 - 测试实现细节而不是可见的 UI 行为。
Final tip
每个组件从核心用户操作开始写一个测试。
你不需要在第一天就写 100 条测试——小而稳定的测试比大量脆弱的测试更好。
接下来的步骤可以包括添加覆盖率报告并在 CI 中运行 Vitest。