跳轉到

5.3 在 CI 上執行:GitHub Actions#

為什麼要進 CI?#

本機測試靠人的記性,常常忘。CI(持續整合)讓每次 Pull Request 自動跑 E2E 測試,不通過不能合併——測試才真正成為品質關卡。

建立工作流程檔#

建立 .github/workflows/playwright.yml:

name: Playwright Tests

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

jobs:
  test:
    timeout-minutes: 30
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm

      - name: 安裝依賴
        run: npm ci

      - name: 安裝 Playwright 瀏覽器
        run: npx playwright install --with-deps chromium

      - name: 執行 E2E 測試
        run: npx playwright test
        env:
          CI: true

      - uses: actions/upload-artifact@v4
        if: ${{ !cancelled() }}          # 失敗也要上傳
        with:
          name: playwright-report
          path: playwright-report/
          retention-days: 30

重點解說:

  • npm ci:依 lock 檔安裝,比 npm install 快且版本精確
  • --with-deps:連系統依賴一起裝(Linux 必要)
  • CI: true:啟用設定檔裡的 CI 行為(重試 2 次、禁止 .only)
  • 上傳 report artifact:失敗後到 Actions 頁面下載報告與 trace,看得到當時畫面

設定檔的 CI 配套#

// playwright.config.ts
export default defineConfig({
  forbidOnly: !!process.env.CI,        // CI 上有 .only 就失敗
  retries: process.env.CI ? 2 : 0,     // CI 上重試 2 次
  workers: process.env.CI ? 1 : undefined,   // CI 上序列執行(更穩)
  webServer: {
    command: "npm run dev",
    url: "http://localhost:3000",
    reuseExistingServer: !process.env.CI,
  },
});

失敗後怎麼看?#

  1. 到 GitHub 的 Actions 頁面找到失敗的 run
  2. 下載 playwright-report artifact
  3. 解壓縮後執行:
npx playwright show-report playwright-report

會打開 HTML 報告,含截圖、影片、trace。

CI 上 E2E 測試的實務建議#

問題 對策
跑太久 只跑 Chromium、平行化、縮小 E2E 數量
Flaky(時好時壞) retries: 2 + 修掉真正的 flaky 測試
失敗看不到畫面 trace + screenshot retain-on-failure + 上傳 artifact
本機過 CI 壞 版本統一(node-version 鎖定)、時區/語系設定一致

心法:E2E 測試進了 CI 才發揮價值。搭配「失敗自動留 trace + 上傳報告」,團隊才能在遠端有效除錯。