安裝
簡介
Playwright Test 是現代 Web 應用程式的端對端測試框架。它整合了測試執行器、斷言、隔離、平行處理和豐富的工具。Playwright 支援 Chromium、WebKit 和 Firefox,可在 Windows、Linux 和 macOS 上執行,無論是本機或在 CI 環境中,支援無頭或有頭模式,並提供 Chrome (Android) 和 Mobile Safari 的原生行動裝置模擬。
您將學習
安裝 Playwright
使用以下其中一種方法安裝 Playwright 來開始使用。
使用 npm、yarn 或 pnpm
下面的指令可初始化新專案或將 Playwright 加入現有專案。
- npm
- yarn
- pnpm
npm init playwright@latest
yarn create playwright
pnpm create playwright
當提示時,選擇/確認:
- TypeScript 或 JavaScript(預設:TypeScript)
- 測試資料夾名稱(預設:
tests
,若tests
已存在則為e2e
) - 加入 GitHub Actions 工作流程(建議用於 CI)
- 安裝 Playwright 瀏覽器(預設:是)
您可以之後重新執行此指令;它不會覆蓋現有測試。
使用 VS Code 擴充功能
您也可以使用 VS Code 擴充功能建立並執行測試。
安裝了什麼
Playwright 會下載所需的瀏覽器二進制檔案並建立如下架構。
playwright.config.ts # 測試組態
package.json
package-lock.json # 或 yarn.lock / pnpm-lock.yaml
tests/
example.spec.ts # 最小範例測試
tests-examples/
demo-todo-app.spec.ts # 更豐富的範例測試
playwright.config 集中管理組態:目標瀏覽器、逾時、重試、專案、報告器等等。在現有專案中,相依套件會加入到您目前的 package.json
。
tests/
包含最小的入門測試。tests-examples/
提供更豐富的範例(例如 todo 應用程式)來探索模式。
執行範例測試
預設情況下,測試會在 Chromium、Firefox 和 WebKit 上以無頭模式平行執行(可在 playwright.config 中設定)。輸出和彙總結果會顯示在終端機中。
- npm
- yarn
- pnpm
npx playwright test
yarn playwright test
pnpm exec playwright test
提示:
- 查看瀏覽器視窗:加入
--headed
。 - 執行單一專案/瀏覽器:
--project=chromium
。 - 執行單一檔案:
npx playwright test tests/example.spec.ts
。 - 開啟測試 UI:
--ui
。
詳細內容請參閱執行測試,包括篩選、有頭模式、分片和重試。
HTML 測試報告
測試執行後,HTML 報告器提供可依瀏覽器、通過、失敗、跳過、不穩定等篩選的儀表板。點擊測試可檢查錯誤、附件和步驟。它只在發生失敗時自動開啟;使用下面的指令手動開啟。
- npm
- yarn
- pnpm
npx playwright show-report
yarn playwright show-report
pnpm exec playwright show-report
在 UI 模式下執行範例測試
使用 UI 模式執行測試,提供監看模式、即時步驟檢視、時光倒流偵錯等功能。
- npm
- yarn
- pnpm
npx playwright test --ui
yarn playwright test --ui
pnpm exec playwright test --ui
詳細的 UI 模式指南請參閱監看篩選器、步驟詳情和追蹤整合。
更新 Playwright
更新 Playwright 並下載新的瀏覽器二進制檔案及其相依套件:
- npm
- yarn
- pnpm
npm install -D @playwright/test@latest
npx playwright install --with-deps
yarn add --dev @playwright/test@latest
yarn playwright install --with-deps
pnpm install --save-dev @playwright/test@latest
pnpm exec playwright install --with-deps
檢查您安裝的版本:
- npm
- yarn
- pnpm
npx playwright --version
yarn playwright --version
pnpm exec playwright --version
系統需求
- Node.js:最新的 20.x、22.x 或 24.x。
- Windows 11+、Windows Server 2019+ 或 Windows Subsystem for Linux (WSL)。
- macOS 14 (Ventura) 或更新版本。
- Debian 12 / 13、Ubuntu 22.04 / 24.04 (x86-64 或 arm64)。