安装
简介
Playwright Test 是一个适用于现代 Web 应用的端到端测试框架。它捆绑了测试运行器、断言、隔离、并行化和丰富的工具。Playwright 支持在 Windows、Linux 和 macOS 上的 Chromium、WebKit 和 Firefox,无论是在本地还是在 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 # Test configuration
package.json
package-lock.json # Or yarn.lock / pnpm-lock.yaml
tests/
example.spec.ts # Minimal example test
tests-examples/
demo-todo-app.spec.ts # Richer example tests
playwright.config 集中了配置:目标浏览器、超时、重试、项目、报告器等等。在现有项目中,依赖项会添加到您当前的 package.json
中。
tests/
包含一个最小的入门测试。tests-examples/
提供了更丰富的示例(例如一个待办事项应用)以探索各种模式。
运行示例测试
默认情况下,测试将在 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
有关监视筛选、步骤详情和 trace 集成的详细信息,请参阅 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 10+、Windows Server 2016+ 或适用于 Linux 的 Windows 子系统 (WSL)。
- macOS 14 (Ventura) 或更高版本。
- Debian 12 / 13, Ubuntu 22.04 / 24.04 (x86-64 或 arm64)。