如何在 GitHub Actions 中利用 Playwright 对文档站点进行视觉回归测试?
解读
国内技术文档团队普遍采用“文档即代码”工作流:Markdown/MDX 源文件托管在 GitHub/Gitee,通过 VitePress、Docusaurus 或自建 VuePress 生成静态站点,再借助 GitHub Actions 完成 CI/CD。视觉回归测试(Visual Regression Testing, VRT)是保障文档迭代不“破图”“走样”的最后一道防线。面试官问“GitHub Actions + Playwright 做 VRT”,表面看是测试方案,实则考察候选人能否把“文档质量”左移到流水线,兼顾成本、效率、合规(源码不出境)、可维护性,并给出国内网络、License、存储、通知等落地细节。
知识点
- Playwright Test 内置 toHaveScreenshot() 断言,自动生成、比对、更新像素级基准图,支持阈值、裁剪、掩码、抗抖动。
- GitHub Actions 国内镜像源:actions 缓存走 ghproxy.com 或自建 MinIO; playwright 安装浏览器可改 PLAYWRIGHT_DOWNLOAD_HOST=https://npmmirror.com/mirrors/playwright。
- 视觉基准图(golden files)体积大,需托管在 repo 的 LFS 或国内 OSS(如阿里云 OSS、腾讯 COS),通过 OIDC 临时密钥上传下载,避免把 AK/SK 写进 YAML。
- 差异审批流:PR 阶段仅做 “shadow 模式” 收集差异报告,评论到 PR;合并到 main 后才更新基准图,防止 feature 分支污染主干基线。
- 合规与成本:截图不含用户隐私;并行 job 数受限于团队 GitHub 套餐,可用 matrix 分片 + 自托管 Runner(华为云 CCE 或阿里云 ACK)降低分钟数。
- 文档特有场景:多主题(暗黑/亮色)、多语言、响应式断点、代码高亮、Mermaid 图、搜索弹窗,都要在测试矩阵里单独截图。
- 失败通知:飞书/钉钉群机器人通过 repo secret 传入 webhook,消息卡片直接展示差异图 URL,一键审批。
答案
给出一个可直接落地的 CI 方案,分五步回答:
第一步,准备 playwright 配置
项目根目录新建 playwright.config.ts,核心片段:
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './vrt',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 4 : undefined,
reporter: [
['html', { outputFolder: 'playwright-report', open: 'never' }],
['json', { outputFile: 'playwright-results.json' }]
],
use: {
baseURL: 'http://localhost:5173', // VitePress dev 端口
trace: 'retain-on-failure',
screenshot: 'only-on-failure',
viewport: { width: 1280, height: 720 },
},
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'mobile', use: { ...devices['iPhone 12'] } }
],
});
第二步,编写视觉测试用例
vrt/docs.spec.ts 示例:
import { test, expect } from '@playwright/test';
test.beforeEach(async ({ page }) => {
await page.goto('/');
// 等待文档 hydration 完成
await page.waitForSelector('article.vp-doc');
});
test('home visual', async ({ page }) => {
await expect(page).toHaveScreenshot('home.png', { fullPage: true });
});
test('api guide dark mode', async ({ page }) => {
await page.click('button[title="Toggle dark mode"]');
await page.goto('/api/');
await expect(page).toHaveScreenshot('api-dark.png', { fullPage: true });
});
第三步,GitHub Actions 工作流 .github/workflows/vrt.yml
name: Docs VRT
on:
pull_request:
paths: ['docs/**', 'vrt/**']
push:
branches: [main]
env:
PLAYWRIGHT_DOWNLOAD_HOST: https://npmmirror.com/mirrors/playwright
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
lfs: true
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- run: npm ci
- name: Install Playwright
run: npx playwright install --with-deps chromium
- name: Build docs
run: npm run docs:build
- name: Start docs server
run: |
npm run docs:preview &
npx wait-on http://localhost:5173
- name: Run VRT
id: vrt
run: npx playwright test
- name: Upload report
if: always()
uses: actions/upload-artifact@v4
with:
name: playwright-report
path: playwright-report/
retention-days: 7
- name: Upload diff to OSS
if: failure() && steps.vrt.outcome == 'failure'
run: |
tar -czf diff.tgz playwright-report/
aliyun oss cp diff.tgz oss://docs-vrt/diff/${{ github.event.number }}/diff.tgz --region cn-hangzhou
env:
ALIBABA_CLOUD_ROLE_ARN: ${{ secrets.OSS_ROLE_ARN }}
ALIBABA_CLOUD_OIDC_TOKEN_FILE: /tmp/oidc
- name: Comment PR
if: github.event_name == 'pull_request' && failure()
uses: actions/github-script@v7
with:
script: |
const url = `https://docs-vrt.oss-cn-hangzhou.aliyuncs.com/diff/${context.issue.number}/diff.tgz`;
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: `🚨 视觉回归检测失败,[差异报告](${url})`
});
update-snapshots:
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- run: npm ci
- run: npx playwright install --with-deps chromium
- run: npm run docs:build
- run: |
npm run docs:preview &
npx wait-on http://localhost:5173
- run: npx playwright test --update-snapshots
- name: Commit new snapshots
run: |
git config user.name "github-actions"
git config user.email "github-actions@github.com"
git add vrt/**/*.png
git diff --cached --quiet || (git commit -m "chore(vrt): update snapshots" && git push)
第四步,OSS 权限与 LFS 二选一
若团队已启用 Git LFS,把 *.png filter=lfs diff=lfs merge=lfs 写进 .gitattributes,CI 直接 lfs: true 即可;否则用 OIDC 方式授权 Actions 临时访问 OSS,避免 AK/SK 泄露。
第五步,本地开发体验
package.json 加脚本:
"test:vrt": "playwright test",
"test:vrt:update": "playwright test --update-snapshots"
开发者本地运行 npm run test:vrt:update 后,通过 git add vrt/**/*.png 提交,保证 baseline 与本地一致,减少 CI 误报。
拓展思考
- 如果文档站点部署在 Gitee Pages,CI 需改用 Gitee Go,镜像源换成清华源,OSS 换成华为云 OBS,OIDC 换成临时安全凭证。
- 对于频繁更新的国际化文档,可把 locale + theme + viewport 三维矩阵拆成 job matrix,并行 20+ 浏览器实例,CI 时间从 15 min 降到 3 min,但需购买 GitHub Team 或自托管 Runner。
- 视觉差异阈值并非越小越好,技术文档含大量代码块抗锯齿差异,建议 threshold=0.2 并启用
maxDiffPixels=200;对 Mermaid 图等动态 SVG 使用mask: [{selector: '.mermaid'}]跳过。 - 长期维护需定期“视觉基线大扫除”:每季度删除无用截图,压缩 PNG(pngquant),LFS 存储量可下降 60%。
- 若公司强制源码不出境,可把 Playwright 容器镜像同步到阿里云 ACR,GitHub Actions 使用
runs-on: self-hosted调用内网 Runner,实现“纯私有”视觉回归闭环。