用途
视觉回归测试(Visual Regression Testing)用于捕获意外的 UI 变更,通过在不同构建之间对比截图来发现视觉差异。
主要能力
Playwright 视觉对比
生成基线截图:
# Run visual tests and create baseline
npx playwright test --update-snapshots
# Run specific visual test file
npx playwright test visual.spec.ts --update-snapshots
运行对比:
# Compare against baseline
npx playwright test visual.spec.ts
# With specific threshold (0 = exact, 0.2 = 20% tolerance)
# Set in test file: expect(page).toHaveScreenshot({ maxDiffPixelRatio: 0.01 })
测试示例:
// visual.spec.ts
import { test, expect } from '@playwright/test';
test('homepage visual', async ({ page }) => {
await page.goto('http://localhost:3000');
await expect(page).toHaveScreenshot('homepage.png', {
fullPage: true,
maxDiffPixelRatio: 0.01,
});
});
test('component visual', async ({ page }) => {
await page.goto('http://localhost:3000/components');
const card = page.locator('.card').first();
await expect(card).toHaveScreenshot('card-component.png');
});
test('responsive visual', async ({ page }) => {
await page.setViewportSize({ width: 375, height: 812 });
await page.goto('http://localhost:3000');
await expect(page).toHaveScreenshot('homepage-mobile.png', { fullPage: true });
});
Percy(云端视觉测试)
# Install
npm install --save-dev @percy/cli @percy/playwright
# Run with Percy snapshots
npx percy exec -- npx playwright test
# Percy environment
export PERCY_TOKEN=your_token_here
在测试中使用 Percy:
import { percySnapshot } from '@percy/playwright';
test('homepage', async ({ page }) => {
await page.goto('http://localhost:3000');
await percySnapshot(page, 'Homepage');
});
Chromatic(Storybook 视觉测试)
# Install
npm install --save-dev chromatic
# Run visual tests against Storybook
npx chromatic --project-token=$CHROMATIC_TOKEN
# Accept all changes (after review)
npx chromatic --project-token=$CHROMATIC_TOKEN --auto-accept-changes
手动截图对比
# Take screenshots with Playwright CLI
npx playwright screenshot http://localhost:3000 before.png
# Make changes, then:
npx playwright screenshot http://localhost:3000 after.png
# Compare with ImageMagick
compare before.png after.png diff.png
identify -verbose diff.png | grep -i "mean"
使用方式
根据项目情况选择方案:本地项目可使用 Playwright 内置截图对比;需要跨浏览器和响应式自动对比时可使用 Percy 或 Chromatic,但需要云端账户。
适用场景
- 前端页面整体视觉验证
- 单个组件视觉验证
- 响应式布局(如移动端视口)视觉验证
- Storybook 组件库视觉测试
限制与注意事项
- 快照与操作系统和浏览器相关,应在 CI 中生成基线,而非本地。
- 使用 maxDiffPixelRatio 而非精确匹配——抗锯齿会在不同环境产生 1 像素差异。
- Percy/Chromatic 自动处理跨浏览器和响应式对比,但需要云端账户。
- 视觉测试较慢,应作为独立的 CI 任务运行,而非与单元测试一起运行。
- 需仔细审查视觉差异——自动批准会失去测试意义。