安装
简介
Playwright Test 专为满足端到端测试需求而创建。Playwright 支持所有现代渲染引擎,包括 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
文件夹,其中包含用于测试待办事项应用程序的测试。
运行示例测试
默认情况下,测试将使用 3 个 worker 在所有 3 个浏览器(Chromium、Firefox 和 WebKit)上运行。这可以在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 14 Ventura 或更高版本。
- Debian 12、Ubuntu 22.04、Ubuntu 24.04,适用于 x86-64 和 arm64 架构。