现在位置: 首页 > Playwright 教程 > 正文

Playwright CI/CD 集成

本章介绍如何将 Playwright 测试集成到 CI/CD 流水线中,包括 GitHub Actions 和其他常见 CI 平台。


GitHub Actions 集成

当你在 npm init playwright@latest 时选择添加 GitHub Actions,Playwright 会自动生成工作流配置。

自动生成的工作流

实例

# 文件路径:.github/workflows/playwright.yml
name
: Playwright Tests

on
:
  push
:
    branches
: [main, master]
  pull_request
:
    branches
: [main, master]

jobs
:
  test
:
    timeout-minutes
: 60
    runs-on
: ubuntu-latest
    steps
:
      - uses
: actions/checkout@v4      # 1. 检出代码
      - uses
: actions/setup-node@v4     # 2. 安装 Node.js
        with
:
          node-version
: 20
      - name
: Install dependencies
        run
: npm ci                     # 3. 安装依赖
      - name
: Install Playwright Browsers
        run
: npx playwright install --with-deps  # 4. 安装浏览器及系统依赖
      - name
: Run Playwright tests
        run
: npx playwright test        # 5. 运行测试
      - uses
: actions/upload-artifact@v4
        if
: always()                    # 6. 上传测试报告(即使测试失败也上传)
        with
:
          name
: playwright-report
          path
: playwright-report/
          retention-days
: 30

查看 CI 测试结果

查看测试日志

在 GitHub 仓库的 Actions 页面中,点击每次运行可以查看详细的测试日志。

每个 Worker 的输出都会独立显示,方便定位特定失败的测试。

查看 HTML 报告

如果配置了 reporter: 'html',可以从 Artifacts 下载 playwright-report/ 来本地查看完整的 HTML 报告。

发布报告到 Web

实例

# 文件路径:.github/workflows/playwright.yml
# 将 HTML 报告部署到 GitHub Pages(简化示例)
- name
: Upload report
  uses
: actions/upload-artifact@v4
  if
: always()
  with
:
    name
: playwright-report
    path
: playwright-report/
    retention-days
: 30

其他 CI 平台

Jenkins

pipeline {
  agent any
  stages {
    stage('Install') {
      steps {
        sh 'npm ci'
        sh 'npx playwright install --with-deps'
      }
    }
    stage('Test') {
      steps {
        sh 'npx playwright test'
      }
    }
  }
  post {
    always {
      archiveArtifacts artifacts: 'playwright-report/**'
      junit 'test-results/junit.xml'
    }
  }
}

GitLab CI

实例

# 文件路径:.gitlab-ci.yml
playwright-tests
:
  image
: mcr.microsoft.com/playwright:v1.52.0-jammy
  script
:
   - npm ci
    - npx playwright test
  artifacts
:
    when
: always
    paths
:
     - playwright-report/
    expire_in
: 30 days

Docker 运行 Playwright

微软提供了预装所有系统依赖的官方 Docker 镜像,开箱即用。

使用官方镜像

# 拉取镜像
docker pull mcr.microsoft.com/playwright:v1.52.0-jammy

# 在容器中运行测试
docker run --rm -v $(pwd):/work -w /work \
  mcr.microsoft.com/playwright:v1.52.0-jammy \
  npx playwright test

Dockerfile 示例

实例

# 文件路径:Dockerfile
FROM mcr.microsoft.com/playwright:v1.52.0-jammy

WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .

CMD ["npx", "playwright", "test"]

CI 环境最佳实践

实践说明
使用 --with-depsnpx playwright install --with-deps 自动安装 Linux 系统依赖
锁定 Playwright 版本package.json 中锁定 @playwright/test 版本,避免 CI 上意外升级
缓存浏览器缓存 ms-playwright 目录,避免每次都下载浏览器
控制 workers 数量使用 workers: process.env.CI ? 1 : undefined 在 CI 上控制资源使用
设置超时CI 环境比本地慢,适当增加 timeoutretries
保留测试产物上传 Trace、截图、视频和报告作为 CI Artifacts