設定檔與多瀏覽器/裝置
playwright.config.ts 集中管理整個測試專案的行為,避免在每支測試裡重複設定相同參數。這一頁整理最常用到的設定項目。
常用全域設定(use)
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
timeout: 30_000, // 單一測試逾時時間
expect: { timeout: 5_000 }, // 斷言逾時時間
fullyParallel: true,
forbidOnly: !!process.env.CI, // CI 上禁止殘留 test.only
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 2 : undefined,
reporter: [['html'], ['list']],
use: {
baseURL: 'http://localhost:3000',
trace: 'on-first-retry', // 失敗重試時才記錄 Trace,節省空間
screenshot: 'only-on-failure',
video: 'retain-on-failure',
},
});
baseURL設定後,測試中可以直接用相對路徑:page.goto('/login')等同於page.goto('http://localhost:3000/login')。trace/screenshot/video建議設成「只在失敗時保留」,兼顧除錯需求與儲存空間,詳見 Trace Viewer 追蹤除錯。
用 projects 設定多瀏覽器與裝置
export default defineConfig({
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'firefox', use: { ...devices['Desktop Firefox'] } },
{ name: 'webkit', use: { ...devices['Desktop Safari'] } },
{ name: 'mobile-safari', use: { ...devices['iPhone 13'] } },
{ name: 'mobile-chrome', use: { ...devices['Pixel 7'] } },
],
});
同一份測試程式碼會在每個 project 各執行一次,等於同時涵蓋桌面三大瀏覽器引擎與行動裝置模擬,不需要為每種環境另外寫測試。執行時可用 --project 指定只跑特定環境:
啟動本機開發伺服器(webServer)
測試通常需要對應的網站先啟動,webServer 可以讓 Playwright 自動處理:
export default defineConfig({
webServer: {
command: 'npm run dev',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI,
},
});
執行 npx playwright test 時會自動啟動開發伺服器、等待網址可連線後才開始測試,結束後自動關閉,CI 環境下通常會設定 reuseExistingServer: false 確保每次都是乾淨的啟動。
依環境切換設定
常見作法是用環境變數區分本機與 CI,或用多個設定檔(如 playwright.staging.config.ts)分別對應不同環境,執行時用 --config 指定:
下一步
設定好測試行為後,接著看 除錯與工具,學習用 Codegen、UI Mode、Trace Viewer 加速開發與除錯。