安装
简介
Playwright Test 专门为满足端到端测试的需求而创建。Playwright 支持所有现代渲染引擎,包括 Chromium、WebKit 和 Firefox。在 Windows、Linux 和 macOS 上进行测试,本地或在 CI 上,无头或有头模式,并原生模拟 Android 版 Google Chrome 和移动版 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
文件夹,其中包含为测试 todo 应用程序而编写的测试。
运行示例测试
默认情况下,测试将在所有 3 个浏览器 (Chromium、Firefox 和 WebKit) 上使用 3 个工作进程运行。这可以在 playwright.config 文件中配置。测试以无头模式运行,这意味着运行测试时不会打开浏览器。测试结果和测试日志将显示在终端中。
- npm
- yarn
- pnpm
npx playwright test
yarn playwright test
pnpm exec playwright test
请参阅我们的关于 运行测试 的文档,以了解有关在有头模式下运行测试、运行多个测试、运行特定测试等的更多信息。
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
# Also download new browser binaries and their dependencies:
npx playwright install --with-deps
yarn add --dev @playwright/test@latest
# Also download new browser binaries and their dependencies:
yarn playwright install --with-deps
pnpm install --save-dev @playwright/test@latest
# Also download new browser binaries and their dependencies:
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+ 或 Linux 的 Windows 子系统 (WSL)。
- macOS 13 Ventura 或更高版本。
- Debian 12、Ubuntu 22.04、Ubuntu 24.04,在 x86-64 和 arm64 架构上。