安装

简介

Playwright Test 是专为满足端到端测试需求而创建的。Playwright 支持所有现代渲染引擎,包括 ChromiumWebKitFirefox。可以在 WindowsLinuxmacOS 上进行测试,无论是本地运行还是 CI 环境,支持无头模式或有头模式,并支持 Google ChromeAndroid 移动端模拟和 Mobile Safari 的原生移动模拟。

你将学到:

  • 如何安装 Playwright

  • 安装了哪些内容

  • 如何运行示例测试

  • 如何打开 HTML 测试报告

安装 Playwright

通过使用 npmyarnpnpm 安装 Playwright 开始。或者,你也可以使用 VS Code 扩展来开始并运行你的测试。

  • npm

  • yarn

  • pnpm

npm init playwright@latest
yarn create playwright
pnpm create playwright

运行安装命令并选择以下选项开始:

  • 选择 TypeScriptJavaScript(默认是 TypeScript

  • 测试文件夹的名称(如果你的项目中已有 tests 文件夹,默认是 testse2e

  • 添加 GitHub Actions 工作流,轻松在 CI 上运行测试

  • 安装 Playwright 浏览器(默认是安装)

安装了哪些内容

Playwright 将下载所需的浏览器并创建以下文件:

playwright.config.ts
package.json
package-lock.json
tests/
  example.spec.ts
tests-examples/
  demo-todo-app.spec.ts

playwright.config.ts 文件是你可以添加 Playwright 配置的地方,包括修改你希望 Playwright 运行的浏览器。如果你在现有项目中运行测试,依赖项将直接添加到你的 package.json 文件中。

tests 文件夹包含一个基本的示例测试,帮助你开始进行测试。欲了解更详细的示例,可以查看 tests-examples 文件夹,该文件夹包含用于测试待办事项应用程序的测试。

运行示例测试

默认情况下,测试将在三个浏览器上运行:ChromiumFirefoxWebKit,使用三个工作线程。可以在 playwright.config.ts 文件中进行配置。测试将在无头模式下运行,这意味着在运行测试时不会打开浏览器。测试结果和日志将显示在终端中。

  • npm

  • yarn

  • pnpm

npx playwright test
yarn playwright test
pnpm exec playwright test
image 2024 12 15 20 23 59 040

命令行中 【运行测试】,了解更多关于如何在有头模式下运行测试、运行多个测试、运行特定测试等的信息,请参考我们的运行测试文档。

HTML 测试报告

测试完成后,将生成一个 【HTML 报告】,显示所有测试的完整报告,允许你按浏览器、通过的测试、失败的测试、跳过的测试和不稳定的测试进行筛选。你可以点击每个测试,查看测试错误以及每个步骤的详细信息。如果某些测试失败,默认情况下 HTML 报告会自动打开。

  • npm

  • yarn

  • pnpm

npx playwright show-report
yarn playwright show-report
pnpm exec playwright show-report
image 2024 12 15 20 25 49 148

运行示例测试(UI 模式)

在 【UI 模式】 下运行你的测试,提供更好的开发者体验,包括时间旅行调试、观察模式等功能。

  • npm

  • yarn

  • pnpm

npx playwright test --ui
yarn playwright test --ui
pnpm exec playwright test --ui
image 2024 12 15 20 29 06 917

【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 及以上

  • Windows 10 及以上版本,Windows Server 2016 及以上版本,或 Windows 子系统 Linux (WSL)

  • macOS 13 Ventura 或更高版本

  • Debian 12、Ubuntu 22.04、Ubuntu 24.04,支持 x86-64 和 arm64 架构

接下来做什么

  • 使用 Web 优先断言、页面 Fixtures 和定位器编写测试

  • 运行单个测试、多重测试、有头模式测试

  • 使用 Codegen 生成测试

  • 查看你的测试追踪