在現代 Web 開發流程中,自動化測試已經成為持續整合(CI)不可或缺的一環。而 Playwright 作為一個功能強大的 E2E 測試框架,搭配 Azure DevOps Pipeline,可以有效地讓我們在每次 commit 或 PR 時,自動進行跨瀏覽器測試,確保系統品質。

本文將介紹如何從零開始,將 Playwright 測試整合進 Azure DevOps CI 流程。


環境準備

  1. 專案初始化
npm init -y
npm install -D @playwright/test
npx playwright install
  1. 新增基本測試檔案(如 tests/example.spec.ts
import { test, expect } from '@playwright/test';

test('首頁標題應正確', async ({ page }) => {
  await page.goto('https://study4.tw');
  await expect(page).toHaveTitle(/study4/);
});
  1. package.json 中加入測試腳本
"scripts": {
  "test": "npx playwright test"
}

設定 Azure DevOps Pipeline

  1. 在專案根目錄新增 .azure-pipelines.yml
trigger:
  - main

pool:
  vmImage: 'ubuntu-latest'

steps:
  - task: NodeTool@0
    inputs:
      versionSpec: '18.x'
    displayName: 'Install Node.js'

  - script: |
      npm install
      npx playwright install --with-deps      
    displayName: 'Install dependencies'

  - script: npm run test
    displayName: 'Run Playwright tests'
  1. Commit 並 Push 上 repo,即可自動觸發 CI,跑完測試。

加分技巧:測試報告整合

Playwright 內建 HTML 測試報告功能,可透過以下指令產出:

npx playwright show-report

若要在 Azure DevOps 呈現報告,可以加上下列任務:

  - task: PublishPipelineArtifact@1
    inputs:
      targetPath: 'playwright-report'
      artifact: 'e2e-report'
      publishLocation: 'pipeline'