测试体系:Vitest + Testing Library + Playwright
前端测试分三层:
单元测试(Unit) Vitest
↓ 测纯函数 / 单个组件 / 工具
集成测试(Integration) Vitest + Testing Library
↓ 测组件交互 / 状态变化 / 多组件协作
端到端测试(E2E) Playwright
↓ 测真实浏览器里的整个用户流程金字塔比例:多写单元,适量集成,少量 E2E。
为什么?
单元 :快(毫秒级),稳定,定位精准
集成 :中(几秒),覆盖业务逻辑
E2E :慢(几十秒),容易 flaky,但最像真实用户这一篇带你把三层都搭起来,讲实战手法和常见 trap。
一、测试金字塔的现代调整
传统金字塔(2010s)
E2E
/ \
Integration
/ \
Unit (大量)
现代实践(2025)
E2E(关键路径)
/ \
Integration(主力)
/ \
Unit (纯函数 / 工具)写法演进:
- 旧:用 Jest + Enzyme 测实现细节(state、props、内部方法)
- 新:用 Vitest + Testing Library 测用户行为("点了按钮看到弹窗")
Testing Library 哲学:
"用户怎么用就怎么测,不测内部实现"二、Vitest:单元测试主力
1. 安装
pnpm add -D vitest @vitest/ui @testing-library/jest-domvite.config.ts:
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true, // 不用 import { it, expect }
environment: 'jsdom', // 测 DOM 用 jsdom
setupFiles: ['./test/setup.ts'],
coverage: {
provider: 'v8',
reporter: ['text', 'html'],
},
},
});// test/setup.ts
import '@testing-library/jest-dom/vitest';2. 第一个测试
// add.ts
export function add(a: number, b: number) { return a + b; }// add.test.ts
import { describe, it, expect } from 'vitest';
import { add } from './add';
describe('add', () => {
it('adds two numbers', () => {
expect(add(1, 2)).toBe(3);
});
it('handles negatives', () => {
expect(add(-1, 1)).toBe(0);
});
});pnpm vitest # 监听模式
pnpm vitest run # 跑一次
pnpm vitest --ui # UI 模式Vitest 用 ESM + 利用 Vite 转译,比 Jest 快 5~10 倍,且配置兼容 Jest API。
3. 常用断言
expect(value).toBe(1); // ===
expect(value).toEqual({ a: 1 }); // 深度
expect(value).toStrictEqual({ a: 1 }); // 更严(类型也比)
expect(arr).toContain(1);
expect(arr).toHaveLength(3);
expect(value).toBeTruthy();
expect(value).toBeNull();
expect(value).toBeUndefined();
expect(fn).toThrow();
expect(fn).toThrow('error message');
expect(promise).resolves.toBe(1);
expect(promise).rejects.toThrow();
// 部分匹配
expect(obj).toMatchObject({ a: 1 });
expect(arr).toEqual(expect.arrayContaining([1, 2]));
expect(obj).toEqual(expect.objectContaining({ a: 1 }));4. Mock
import { vi } from 'vitest';
// mock 函数
const fn = vi.fn();
fn(1);
expect(fn).toHaveBeenCalled();
expect(fn).toHaveBeenCalledWith(1);
expect(fn).toHaveBeenCalledTimes(1);
// mock 模块
vi.mock('./api', () => ({
fetchUser: vi.fn(() => Promise.resolve({ id: '1', name: 'A' }))
}));
// spy 现有方法
const spy = vi.spyOn(console, 'log');
spy.mockImplementation(() => {});
// mock 时间
vi.useFakeTimers();
vi.advanceTimersByTime(1000);
vi.runAllTimers();
vi.useRealTimers();5. 异步测试
it('fetches data', async () => {
const data = await fetchUser('1');
expect(data).toEqual({ id: '1', name: 'A' });
});
// 或返回 Promise
it('fetches', () => {
return fetchUser('1').then(d => expect(d.id).toBe('1'));
});
// 测错误
it('throws on bad id', async () => {
await expect(fetchUser('bad')).rejects.toThrow();
});6. 钩子
beforeAll(() => { /* 全文件前 */ });
afterAll(() => { /* 全文件后 */ });
beforeEach(() => { /* 每个 it 前 */ });
afterEach(() => { /* 每个 it 后 */ });7. 参数化测试(it.each)
it.each([
[1, 1, 2],
[2, 3, 5],
[-1, 1, 0],
])('add(%i, %i) = %i', (a, b, expected) => {
expect(add(a, b)).toBe(expected);
});三、Testing Library:测组件
1. 哲学
"如果用户能看到 / 能交互的,就能测;
内部实现(state、props 名字、方法名)不测。"好处:重构内部代码,测试不挂。
2. 安装(React 例)
pnpm add -D @testing-library/react @testing-library/user-event @testing-library/jest-dom3. 第一个组件测试
// 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>
);
}// Counter.test.tsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Counter } from './Counter';
it('increments on click', async () => {
render(<Counter />);
// 通过用户能看到的内容查找
expect(screen.getByText('Count: 0')).toBeInTheDocument();
await userEvent.click(screen.getByRole('button', { name: /increment/i }));
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});注意:没碰任何内部 state,只看用户能看到的。
4. 查找元素的优先级
1. getByRole ← 最推荐(无障碍 + 用户视角)
2. getByLabelText ← 表单
3. getByPlaceholderText
4. getByText ← 静态文本
5. getByDisplayValue ← 表单当前值
6. getByAltText ← img
7. getByTitle
8. getByTestId ← 最后的兜底// 推荐
screen.getByRole('button', { name: /submit/i });
screen.getByLabelText('Email');
screen.getByText(/welcome/i);
// 兜底
<div data-testid="custom-thing" />
screen.getByTestId('custom-thing');5. get / query / find
getByX : 找不到抛错(确定存在时用)
queryByX : 找不到返回 null(测"不存在"时用)
findByX : 等到出现(异步,Promise),最大等 1 秒// 测出现
expect(await screen.findByText('Loaded')).toBeInTheDocument();
// 测不存在
expect(screen.queryByText('Error')).not.toBeInTheDocument();6. 用户交互(userEvent)
const user = userEvent.setup();
await user.click(button);
await user.dblClick(el);
await user.hover(el);
await user.type(input, 'hello');
await user.clear(input);
await user.keyboard('{Enter}');
await user.selectOptions(select, 'option1');
await user.upload(input, file);
await user.tab();不要用旧的 fireEvent,userEvent 模拟更真实(键盘事件、focus 等连带触发)。
7. 异步组件
function User({ id }: { id: string }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetch(`/api/users/${id}`).then(r => r.json()).then(setUser);
}, [id]);
if (!user) return <p>Loading...</p>;
return <p>Hi {user.name}</p>;
}import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
const server = setupServer(
http.get('/api/users/1', () => HttpResponse.json({ name: 'Alice' }))
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
it('shows user name', async () => {
render(<User id="1" />);
expect(screen.getByText('Loading...')).toBeInTheDocument();
expect(await screen.findByText(/Alice/)).toBeInTheDocument();
});MSW(Mock Service Worker)是 fetch 拦截的事实标准。别 mock fetch,mock 网络层。
8. Vue 例
pnpm add -D @testing-library/vueimport { render, screen } from '@testing-library/vue';
import userEvent from '@testing-library/user-event';
import Counter from './Counter.vue';
it('increments', async () => {
render(Counter);
await userEvent.click(screen.getByRole('button'));
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});API 跟 React Testing Library 一致。
9. Solid 例
pnpm add -D @solidjs/testing-libraryAPI 同样基本一致。
四、MSW:Mock 网络层
为什么不直接 mock fetch
// ❌ 直接 mock fetch
global.fetch = vi.fn(() => Promise.resolve({ json: () => ... }));问题:
- 跟生产代码不一样
- 改 API 时测试不报错
- 不能测请求头、body 等
// ✅ MSW 拦截真实请求
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
const server = setupServer(
http.get('/api/users/:id', ({ params }) => {
return HttpResponse.json({ id: params.id, name: 'Alice' });
}),
http.post('/api/login', async ({ request }) => {
const body = await request.json();
if (body.password !== 'secret') {
return HttpResponse.json({ error: 'wrong' }, { status: 401 });
}
return HttpResponse.json({ token: 'xxx' });
}),
);测试代码用真实 fetch,MSW 在底层拦截。生产环境也能用同样的 mock(开发期)。
单测试覆盖特殊场景
it('handles error', async () => {
server.use(
http.get('/api/users/1', () => HttpResponse.json({}, { status: 500 }))
);
render(<User id="1" />);
expect(await screen.findByText(/error/i)).toBeInTheDocument();
});server.use 临时覆盖,afterEach 自动 reset。
五、Playwright:E2E 测试
1. 安装
pnpm create playwright
# 选 TypeScript、装浏览器、加 GitHub Actionsplaywright.config.ts
tests/
└── example.spec.ts2. 第一个 E2E
import { test, expect } from '@playwright/test';
test('login flow', async ({ page }) => {
await page.goto('http://localhost:3000/login');
await page.getByLabel('Email').fill('alice@example.com');
await page.getByLabel('Password').fill('secret');
await page.getByRole('button', { name: /sign in/i }).click();
await expect(page).toHaveURL(/\/dashboard/);
await expect(page.getByText(/welcome alice/i)).toBeVisible();
});pnpm playwright test # 跑所有
pnpm playwright test --ui # 可视化模式
pnpm playwright test --headed # 看着浏览器跑
pnpm playwright test --debug # 单步调试Playwright 自带 trace viewer:
pnpm playwright show-trace trace.zip录回放每一步,比 Cypress 强。
3. 选择器优先级(同 Testing Library)
page.getByRole('button', { name: /submit/i })
page.getByLabel('Email')
page.getByText(/welcome/i)
page.getByPlaceholder('Search')
page.getByTestId('custom-id')4. 等待与断言
Playwright 有自动等待:click 会等元素可见 + 可点 + 不动。
// 不需要显式 wait
await page.getByRole('button').click(); // 内部已经等了
// 显式等
await page.waitForURL(/\/dashboard/);
await page.waitForResponse(r => r.url().includes('/api/me'));
await expect(page.getByText('Done')).toBeVisible({ timeout: 10000 });不要手写 setTimeout 等待。
5. 多浏览器 / 多设备
// playwright.config.ts
export default defineConfig({
projects: [
{ name: 'chromium', use: devices['Desktop Chrome'] },
{ name: 'firefox', use: devices['Desktop Firefox'] },
{ name: 'webkit', use: devices['Desktop Safari'] },
{ name: 'mobile', use: devices['iPhone 14'] },
],
});跑一次跨四个浏览器。
6. 截图 / 录像
// playwright.config.ts
use: {
screenshot: 'only-on-failure',
video: 'retain-on-failure',
trace: 'retain-on-failure',
}CI 失败时自动留证据。
7. fixture / setup
// 共享登录态
import { test as base } from '@playwright/test';
export const test = base.extend({
authedPage: async ({ page }, use) => {
await page.goto('/login');
await page.getByLabel('Email').fill(...);
await page.getByLabel('Password').fill(...);
await page.getByRole('button').click();
await use(page);
},
});
test('dashboard', async ({ authedPage }) => {
await authedPage.goto('/dashboard');
});或者用 storageState 全局保存登录态(只登一次,后面所有测试复用)。
8. 可视化回归
await expect(page).toHaveScreenshot('dashboard.png');第一次跑生成 baseline,后续跟 baseline 对比像素差异。Playwright 自带,Cypress 要插件。
六、组件测试 vs E2E:谁测什么
| 场景 | Vitest + RTL(组件测试) | Playwright(E2E) |
|---|---|---|
| 按钮 disabled 状态 | ✅ | ❌ 太细 |
| 表单校验 | ✅ | 关键字段才测 |
| 路由跳转 | ⚠️ 装 router-mock | ✅ 真实跳 |
| 登录 + 鉴权 | ⚠️ 模拟 | ✅ 主战场 |
| 多页面流程 | ❌ | ✅ |
| API 错误处理 | ✅ MSW | ⚠️ 难造 |
| 视觉回归 | ❌ | ✅ |
| 性能 / 加载时间 | ❌ | ✅ Lighthouse |
判断标准:能用单元测的就单元测,省钱省时间。E2E 留给"必须看真实浏览器"的场景。
七、覆盖率(Coverage)
pnpm vitest --coverage输出:
File | % Stmts | % Branch | % Funcs | % Lines |
-------------|---------|----------|---------|---------|
add.ts | 100 | 100 | 100 | 100 |
Counter.tsx | 85 | 75 | 100 | 85 |关心:
- Branch:
if/else各分支都测了吗 - Funcs:每个函数都有测了吗
- Lines / Stmts:基础
别盲目追 100%。覆盖率高 ≠ 测试好。100% 覆盖但只断言 expect(true).toBe(true) 一样没用。
实战目标:80% 覆盖,关键业务路径 100%。
八、常见 Trap
Trap 1:测实现细节
// ❌ 测内部 state
const wrapper = mount(<Counter />);
expect(wrapper.state('count')).toBe(0);
// ✅ 测用户看到的
expect(screen.getByText('Count: 0')).toBeInTheDocument();mount / Enzyme 那套已经过时,新项目别学。
Trap 2:act 警告
Warning: An update to X inside a test was not wrapped in act(...)通常:
- 异步状态更新没 await
- 用
userEvent而不是fireEvent - 用
findBy而不是手动 wait
99% 的 act 警告 RTL 都自动处理,出现就是写法不对。
Trap 3:E2E 写"动作链",一断全断
// ❌ 一个文件 50 步
test('full flow', async ({ page }) => {
await login();
await goToDashboard();
await createProject();
await editProject();
await deleteProject();
// 中间一步挂 → 后面全废
});
// ✅ 拆成多个独立测试,共享 setup
test.beforeEach(async ({ page }) => { await login(); });
test('create', async ({ page }) => { ... });
test('edit', async ({ page }) => { ... });Trap 4:E2E 测试不稳定(flaky)
原因 99% 是等待时间不对:
- 用了
setTimeout/waitFor(1000)而不是事件等待 - 网络慢导致超时
- 元素短暂遮挡
修复:
- 用
expect(...).toBeVisible()而不是setTimeout - 加 retry:
retries: 2(CI 环境) - 跑测试前 build 而不是 dev mode(更稳)
Trap 5:测试隔离不干净
// 全局 mock 没还原 → 影响下一个测试
afterEach(() => {
vi.clearAllMocks();
cleanup(); // RTL 的清理函数
});vitest 默认会 cleanup,RTL 集成已自动。
九、CI 集成
# .github/workflows/test.yml
name: Test
on: [push, pull_request]
jobs:
unit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- uses: actions/setup-node@v4
with: { node-version: 20, cache: 'pnpm' }
- run: pnpm install
- run: pnpm vitest run --coverage
e2e:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- uses: actions/setup-node@v4
with: { node-version: 20, cache: 'pnpm' }
- run: pnpm install
- run: pnpm playwright install --with-deps
- run: pnpm build
- run: pnpm playwright test
- uses: actions/upload-artifact@v4
if: failure()
with:
name: playwright-report
path: playwright-report/十、心智模型
测试金字塔(2025):
E2E(关键路径) Playwright,慢但真实
/ \
Integration Vitest + RTL + MSW
/ \ 主力,80% 测试在这
Unit Vitest,纯函数
哲学:
- 测行为,不测实现(Testing Library)
- mock 网络层,不 mock 函数(MSW)
- 自动等待,不手动 setTimeout(Playwright 内置)
- 覆盖率 80% + 关键路径 E2E,不追 100%十一、参考速查
# Vitest
pnpm add -D vitest @vitest/ui jsdom
pnpm vitest # 监听
pnpm vitest run # 一次
# Testing Library
pnpm add -D @testing-library/react @testing-library/user-event @testing-library/jest-dom
# 选元素:getByRole > getByLabelText > getByText > getByTestId
# MSW
pnpm add -D msw
# 在 setup 里 server.listen / resetHandlers / close
# Playwright
pnpm create playwright
pnpm playwright test --ui
pnpm playwright codegen # 录制操作生成代码下一篇 28 讲认证与安全:JWT / Session / OAuth、XSS / CSRF / CSP。