安裝與專案設定
Playwright 提供官方腳手架指令,一次幫你安裝套件、下載瀏覽器、建立範例測試與設定檔,不需要手動拼湊環境。
建立新專案
在 Node.js 專案目錄下執行:
安裝過程會詢問幾個問題:
- 使用 TypeScript 或 JavaScript(建議 TypeScript,型別提示對維護測試很有幫助)。
- 測試放在哪個資料夾(預設
tests)。 - 是否加入 GitHub Actions 工作流程(之後可在 平行執行與 CI/CD 整合 進一步設定)。
- 是否立刻下載 Chromium、Firefox、WebKit 三種瀏覽器。
完成後會產生以下結構:
my-project/
├── tests/
│ └── example.spec.ts # 範例測試
├── tests-examples/
│ └── demo-todo-app.spec.ts
├── playwright.config.ts # 測試設定檔
├── package.json
└── .github/workflows/ # 選填的 CI 設定
認識 playwright.config.ts
設定檔集中管理測試的行為,最常用到的欄位:
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
fullyParallel: true, // 測試檔案平行執行
retries: process.env.CI ? 2 : 0, // CI 上失敗自動重試
reporter: 'html',
use: {
baseURL: 'http://localhost:3000',
trace: 'on-first-retry', // 失敗重試時記錄 Trace
},
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'firefox', use: { ...devices['Desktop Firefox'] } },
{ name: 'webkit', use: { ...devices['Desktop Safari'] } },
],
});
projects 讓同一份測試可以同時在多種瀏覽器、甚至模擬裝置(如 devices['iPhone 13'])上執行,這是 Playwright「一套 API、多種瀏覽器」的核心設計。完整選項見 設定檔與多瀏覽器/裝置。
既有專案安裝
若已有 Node.js 專案,只想加入 Playwright,可分開安裝套件與瀏覽器:
npx playwright install 會下載 Playwright 管理的瀏覽器版本,與系統既有的 Chrome/Firefox 無關,確保測試環境一致、不受本機瀏覽器版本影響。
驗證安裝
若看到測試通過的摘要與 HTML 報表提示,代表安裝成功。接著前往 撰寫並執行第一個測試,動手寫一支屬於自己的測試。