安装指南
简介
Playwright Test 是专为满足端到端测试需求而设计的。它支持所有现代渲染引擎,包括 Chromium、WebKit 和 Firefox。可以在 Windows、Linux 和 macOS 上本地或 CI 环境中运行测试,支持无头模式或有头模式,并提供对 Android 版 Google Chrome 和 Mobile Safari 的原生移动设备模拟。
您将学习
安装 Playwright
首先通过 npm、yarn 或 pnpm 安装 Playwright。您也可以使用 VS Code 扩展 来开始并运行测试。
- npm
- yarn
- pnpm
npm init playwright@latest
yarn create playwright
pnpm create playwright
运行安装命令并选择以下选项开始使用:
- 选择 TypeScript 或 JavaScript(默认为 TypeScript)
- 指定测试文件夹名称(默认为 tests,如果项目中已存在 tests 文件夹则默认为 e2e)
- 添加 GitHub Actions 工作流以便在 CI 上轻松运行测试
- 安装 Playwright 浏览器(默认为 true)
已安装内容
Playwright 会自动下载所需的浏览器并创建以下文件:
playwright.config.ts
package.json
package-lock.json
tests/
example.spec.ts
tests-examples/
demo-todo-app.spec.ts
playwright.config 文件可用于配置 Playwright,包括修改您希望运行 Playwright 的浏览器类型。如果您在已有项目中运行测试,依赖项将直接添加到您的 package.json
文件中。
tests
文件夹包含一个基础测试示例,帮助您开始编写测试。更详细的示例可查看 tests-examples
文件夹,其中包含针对待办事项应用编写的测试用例。
运行示例测试
默认情况下,测试将在 Chromium、Firefox 和 WebKit 三种浏览器上运行,并使用多个工作进程。这可以在 playwright.config 文件 中进行配置。测试以无头模式运行,意味着执行测试时不会打开浏览器窗口。测试结果和日志将显示在终端中。
- npm
- yarn
- pnpm
npx playwright test
yarn playwright test
pnpm exec playwright test
查看我们的 运行测试 文档,了解更多关于在 headed 模式下运行测试、运行多个测试或特定测试等信息。
HTML 测试报告
测试完成后,系统会生成一份 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
您可以通过以下命令随时检查当前安装的 Playwright 版本:
- npm
- yarn
- pnpm
npx playwright --version
yarn playwright --version
pnpm exec playwright --version
系统要求
- Node.js 18、20 或 22 的最新版本
- Windows 10+、Windows Server 2016+ 或 Windows Subsystem for Linux (WSL)
- macOS 14 Ventura 或更高版本
- Debian 12、Ubuntu 22.04、Ubuntu 24.04,支持 x86-64 和 arm64 架构