发行说明
1.58 版本
🌐 Version 1.58
时间轴
🌐 Timeline
如果你正在使用合并报告,HTML 报告的 Speedboard 标签现在会显示时间轴:
🌐 If you're using merged reports, the HTML report Speedboard tab now shows the Timeline:

用户界面模式和跟踪查看器改进
🌐 UI Mode and Trace Viewer Improvements
- 新的“系统”主题选项会跟随你的操作系统深色/浅色模式偏好
- 代码编辑器现在可以使用搜索功能(Cmd/Ctrl+F)
- 网络详细信息面板已重新组织,以提高可用性
- JSON 响应现在会自动格式化以提高可读性
感谢 @cpAdm 对这些改进的贡献!
🌐 Thanks to @cpAdm for contributing these improvements!
杂项
🌐 Miscellaneous
browserType.connectOverCDP() 现在接受一个 isLocal 选项。当设置为 true 时,它告诉 Playwright 它运行在与 CDP 服务器相同的主机上,从而启用文件系统优化。
重大更改 ⚠️
🌐 Breaking Changes ⚠️
- 已移除
_react和_vue选择器。有关替代方案,请参阅 定位器指南。 - 已移除
:light选择器引擎后缀。请改用标准 CSS 选择器。 - 从 browserType.launch() 中移除了选项
devtools。请使用args: ['--auto-open-devtools-for-tabs']替代。 - 已移除对 macOS 13 的 WebKit 支持。我们建议升级你的 macOS 版本,或继续使用较旧的 Playwright 版本。
浏览器版本
🌐 Browser Versions
- Chromium 145.0.7632.6
- Mozilla Firefox 146.0.1
- WebKit 26.0
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- 谷歌浏览器 144
- 微软 Edge 144
1.57 版本
🌐 Version 1.57
速度板
🌐 Speedboard
在 HTML 报告中,有一个我们称之为“速度板”的新标签页:
🌐 In HTML reporter, there's a new tab we call "Speedboard":

它会显示你所有已执行的测试,并按慢速排序,帮助你了解测试套件在哪些地方耗时超出预期。看看你的测试吧——也许你会发现一些测试花费的等待时间比预期更长!
🌐 It shows you all your executed tests sorted by slowness, and can help you understand where your test suite is taking longer than expected. Take a look at yours - maybe you'll find some tests that are spending a longer time waiting than they should!
用于测试的 Chrome
🌐 Chrome for Testing
从此版本开始,Playwright 将从 Chromium 切换为使用 Chrome for Testing 构建版本。无论是有界面还是无界面浏览器,都将受到此更改的影响。升级到 Playwright 1.57 后,你的测试仍应该能够通过。
🌐 Starting with this release, Playwright switches from Chromium, to using Chrome for Testing builds. Both headed and headless browsers are subject to this. Your tests should still be passing after upgrading to Playwright 1.57.
我们预计此次切换不会带来功能上的变化。最大变化是工具栏中的新图标和标题。
🌐 We're expecting no functional changes to come from this switch. The biggest change is the new icon and title in your toolbar.

如果你仍然看到意外的行为变化,请 提交问题。
🌐 If you still see an unexpected behaviour change, please file an issue.
在 Arm64 Linux 上,Playwright 仍然使用 Chromium。
🌐 On Arm64 Linux, Playwright continues to use Chromium.
正在等待网页服务器输出
🌐 Waiting for webserver output
testConfig.webServer 添加了一个 wait 字段。传入一个正则表达式,Playwright 将会等待直到 Web 服务器日志匹配该表达式。
import { defineConfig } from '@playwright/test';
export default defineConfig({
webServer: {
command: 'npm run start',
wait: {
stdout: /Listening on port (?<my_server_port>\d+)/
},
},
});
如果你在表达式中包含一个命名的捕获组,那么 Playwright 会通过环境变量提供该捕获组的内容:
🌐 If you include a named capture group into the expression, then Playwright will provide the capture group contents via environment variables:
import { test, expect } from '@playwright/test';
test.use({ baseURL: `http://localhost:${process.env.MY_SERVER_PORT ?? 3000}` });
test('homepage', async ({ page }) => {
await page.goto('/');
});
这不仅仅用于捕获不同端口的开发服务器。你还可以用它来等待那些没有提供 HTTP 就绪检查的服务准备就绪,而是将就绪消息打印到 stdout 或 stderr 的服务。
🌐 This is not just useful for capturing varying ports of dev servers. You can also use it to wait for readiness of a service that doesn't expose an HTTP readiness check, but instead prints a readiness message to stdout or stderr.
重大变更
🌐 Breaking Change
在被弃用三年后,我们已从 API 中移除了 page.accessibility。如果你需要测试页面的可访问性,请使用其他库,例如 Axe。有关与 Axe 集成的详细信息,请参阅我们的 Node.js 指南。
🌐 After 3 years of being deprecated, we removed page.accessibility from our API. Please use other libraries such as Axe if you need to test page accessibility. See our Node.js guide for integration with Axe.
新 API
🌐 New APIs
- 新属性 testConfig.tag 会为此次运行中的所有测试添加一个标签。当使用 merge-reports 时,这非常有用。
- worker.on('console') 事件在工作进程中的 JavaScript 调用任一控制台 API 方法(例如 console.log 或 console.dir)时触发。worker.waitForEvent() 可以用来等待该事件。
- locator.description() 返回之前使用 locator.describe() 设置的定位器描述,locator.toString() 现在在可用时使用该描述。
- locator.click() 和 locator.dragTo() 中新增了选项 steps,用于配置在将鼠标指针移动到目标元素的过程中触发
mousemove事件的次数。 - 由[服务工作者](./service-workers.mdx#network-events-and-routing)发出的网络请求现在会被报告,并且只能通过BrowserContext(./api/class-browsercontext.mdx)路由,仅限于Chromium版本。你可以选择退出,使用“PLAYWRIGHT_DISABLE_SERVICE_WORKER_NETWORK”环境变量。
- 来自服务工作进程的控制台消息通过 worker.on('console') 分发。你可以使用
PLAYWRIGHT_DISABLE_SERVICE_WORKER_CONSOLE环境变量选择退出此功能。
浏览器版本
🌐 Browser Versions
- Chromium 143.0.7499.4
- Mozilla Firefox 144.0.2
- WebKit 26.0
1.56 版本
🌐 Version 1.56
Playwright 测试代理
🌐 Playwright Test Agents
Playwright 测试代理简介:三个自定义代理定义,旨在指导 LLM 完成构建 Playwright 测试的核心流程:
🌐 Introducing Playwright Test Agents, three custom agent definitions designed to guide LLMs through the core process of building a Playwright test:
- 🎭 planner 探索该应用并生成一个 Markdown 测试计划
- 🎭 生成器 将 Markdown 计划转换为 Playwright 测试文件
- ** 🎭 修复器** 执行测试套件并自动修复失败的测试
使用你选择的客户端运行 npx playwright init-agents 以生成最新的代理定义:
🌐 Run npx playwright init-agents with your client of choice to generate the latest agent definitions:
# Generate agent files for each agentic loop
# Visual Studio Code
npx playwright init-agents --loop=vscode
# Claude Code
npx playwright init-agents --loop=claude
# opencode
npx playwright init-agents --loop=opencode
新 API
🌐 New APIs
- 用于从页面检索最新控制台消息的新方法 page.consoleMessages() 和 page.pageErrors()
- 新方法 page.requests() 用于获取页面的最新网络请求
- 添加了
--test-list和--test-list-invert,以允许从文件手动指定特定测试
UI 模式和 HTML 报告器
🌐 UI Mode and HTML Reporter
- 在
'html'报告器中添加了禁用“复制提示”按钮的选项 - 在“'html'”报告器和UI模式下增加了合并文件、将测试和描述块合并为统一列表的选项
- 在 UI 模式中添加了与
--update-snapshots选项对应的选项 - 在 UI 模式中添加选项,用于一次只运行一个工作进程
重大变化
🌐 Breaking Changes
- 事件 browserContext.on('backgroundpage') 已被弃用,将不会触发。方法 browserContext.backgroundPages() 将返回一个空列表
杂项
🌐 Miscellaneous
- Aria 快照呈现并比较
inputplaceholder - 已向 Playwright 工作进程添加环境变量
PLAYWRIGHT_TEST,以便区分测试状态
浏览器版本
🌐 Browser Versions
- Chromium 141.0.7390.37
- Mozilla Firefox 142.0.1
- WebKit 26.0
1.55 版本
🌐 Version 1.55
新 API
🌐 New APIs
- 新属性 testStepInfo.titlePath 返回从测试文件开始的完整标题路径,包括测试和步骤标题。
代码生成器
🌐 Codegen
- 自动
toBeVisible()断言:Codegen 现在可以为常见的 UI 交互生成自动toBeVisible()断言。此功能可以在 Codegen 设置界面中启用。
重大变化
🌐 Breaking Changes
- ⚠️ 已停止支持 Chromium 扩展清单 v2。
杂项
🌐 Miscellaneous
- 已新增对 Debian 13 “Trixie”的支持。
浏览器版本
🌐 Browser Versions
- Chromium 140.0.7339.16
- Mozilla Firefox 141.0
- WebKit 26.0
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- Google Chrome 139
- Microsoft Edge 139
1.54 版本
🌐 Version 1.54
高亮
🌐 Highlights
-
在 browserContext.cookies() 和 browserContext.addCookies() 中新增了 Cookie 属性
partitionKey。此属性允许保存和恢复分区 Cookie。更多信息请参见 CHIPS MDN 文章。请注意,不同浏览器对 Cookie 分区的支持和默认设置有所不同。 -
新增选项
noSnippets,用于在 HTML 报告中禁用代码片段。import { defineConfig } from '@playwright/test';
export default defineConfig({
reporter: [['html', { noSnippets: true }]]
}); -
测试注释中新增属性
location,例如在 testResult.annotations 和 testInfo.annotations 中。它显示了像test.skip或test.fixme这样的注释是添加在哪个位置。
命令行
🌐 Command Line
-
多个命令中新增选项
--user-data-dir。你可以指定相同的用户数据目录,以便在会话之间重用浏览状态,例如身份验证信息。npx playwright codegen --user-data-dir=./user-data -
npx playwright test命令中的选项-gv已被移除。请改用--grep-invert。 -
npx playwright open不再打开测试录制器。请改用npx playwright codegen。
杂项
🌐 Miscellaneous
- 已移除对 Node.js 16 的支持。
- 已弃用对 Node.js 18 的支持,并将在未来移除。
浏览器版本
🌐 Browser Versions
- Chromium 139.0.7258.5
- Mozilla Firefox 140.0.2
- WebKit 26.0
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- Google Chrome 140
- Microsoft Edge 140
1.53 版本
🌐 Version 1.53
Trace 查看器和 HTML 报告器更新
🌐 Trace Viewer and HTML Reporter Updates
-
Trace Viewer 和 HTML 报告中的新步骤:
-
'html'报告器中新增加的选项,用于设置特定测试运行的标题:import { defineConfig } from '@playwright/test';
export default defineConfig({
reporter: [['html', { title: 'Custom test run #1028' }]]
});
杂项
🌐 Miscellaneous
-
testInfo.snapshotPath() 中的新选项 kind 控制使用哪个快照路径模板。
-
新方法 locator.describe() 用于描述定位器。用于追踪查看器和报告。
const button = page.getByTestId('btn-sub').describe('Subscribe button');
await button.click(); -
npx playwright install --list现在将列出所有已安装的浏览器、版本和位置。
浏览器版本
🌐 Browser Versions
- Chromium 138.0.7204.4
- Mozilla Firefox 139.0
- WebKit 18.5
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- Google Chrome 137
- Microsoft Edge 137
1.52 版本
🌐 Version 1.52
高亮
🌐 Highlights
-
新方法 expect(locator).toContainClass() 可方便地断言元素上的单个类名。
await expect(page.getByRole('listitem', { name: 'Ship v1.52' })).toContainClass('done'); -
Aria 快照 获得了两个新属性:用于严格匹配的
/children和用于链接的/url。await expect(locator).toMatchAriaSnapshot(`
- list
- /children: equal
- listitem: Feature A
- listitem:
- link "Feature B":
- /url: "https://playwright.nodejs.cn"
`);
测试运行器
🌐 Test Runner
- 新属性 testProject.workers 允许指定测试项目使用的并发工作进程数量。全局属性限制 testConfig.workers 仍然适用。
- 新增 testConfig.failOnFlakyTests 选项,如果检测到任何不稳定的测试,则使测试运行失败,类似于
--fail-on-flaky-tests。这在 CI/CD 环境中非常有用,可以确保在部署之前所有测试都是稳定的。 - 新属性 testResult.annotations 包含每次测试重试的注释。
杂项
🌐 Miscellaneous
- 在 apiRequest.newContext() 中新增选项 maxRedirects,用于控制最大重定向次数。
- HTML 报告器现在支持通过
!@my-tag、!my-file.spec.ts或!p:my-project进行非过滤。
重大变化
🌐 Breaking Changes
- 像 page.route() 这样的方法中的通配符 URL 模式不再支持
?和[]。我们建议改用正则表达式。 - 方法 route.continue() 不再允许覆盖
Cookie头。如果提供了Cookie头,它将被忽略,Cookie 将从浏览器的 Cookie 存储中加载。要设置自定义 Cookie,请使用 browserContext.addCookies()。 - macOS 13 已被弃用,将不再接收 WebKit 更新。请升级到更新的 macOS 版本,以继续享受最新的 WebKit 改进。
浏览器版本
🌐 Browser Versions
- Chromium 136.0.7103.25
- Mozilla Firefox 137.0
- WebKit 18.4
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- Google Chrome 135
- Microsoft Edge 135
1.51 版本
🌐 Version 1.51
indexedDB 的存储状态
🌐 StorageState for indexedDB
-
新的选项 indexedDB 用于 browserContext.storageState(),可以保存和恢复 IndexedDB 内容。当你的应用使用 IndexedDB API 存储身份验证令牌(例如 Firebase Authentication)时,这非常有用。
这里有一个按照认证指南的示例:
tests/auth.setup.tsimport { test as setup, expect } from '@playwright/test';
import path from 'path';
const authFile = path.join(__dirname, '../playwright/.auth/user.json');
setup('authenticate', async ({ page }) => {
await page.goto('/');
// ... perform authentication steps ...
// make sure to save indexedDB
await page.context().storageState({ path: authFile, indexedDB: true });
});
按提示复制
🌐 Copy as prompt
HTML 报告、追踪查看器和 UI 模式中的错误新增了“复制提示”按钮。点击即可复制一个预先填写的 LLM 提示,其中包含错误信息和修复错误的有用上下文。
🌐 New "Copy prompt" button on errors in the HTML report, trace viewer and UI mode. Click to copy a pre-filled LLM prompt that contains the error message and useful context for fixing the error.
过滤可见元素
🌐 Filter visible elements
新的选项 visible 用于 locator.filter(),允许仅匹配可见元素。
🌐 New option visible for locator.filter() allows matching only visible elements.
test('some test', async ({ page }) => {
// Ignore invisible todo items.
const todoItems = page.getByTestId('todo-item').filter({ visible: true });
// Check there are exactly 3 visible ones.
await expect(todoItems).toHaveCount(3);
});
HTML 报告中的 Git 信息
🌐 Git information in HTML report
将选项 testConfig.captureGitInfo 设置为将 git 信息捕获到 testConfig.metadata 中。
🌐 Set option testConfig.captureGitInfo to capture git information into testConfig.metadata.
import { defineConfig } from '@playwright/test';
export default defineConfig({
captureGitInfo: { commit: true, diff: true }
});
HTML 报告将在可用时显示此信息:
🌐 HTML report will show this information when available:
测试步骤改进
🌐 Test Step improvements
测试步骤中现在可以使用新的 TestStepInfo 对象。你可以在某些条件下添加步骤附件或跳过该步骤。
🌐 A new TestStepInfo object is now available in test steps. You can add step attachments or skip the step under some conditions.
test('some test', async ({ page, isMobile }) => {
// Note the new "step" argument:
await test.step('here is my step', async step => {
step.skip(isMobile, 'not relevant on mobile layouts');
// ...
await step.attach('my attachment', { body: 'some text' });
// ...
});
});
杂项
🌐 Miscellaneous
- 新选项
contrast可用于方法 page.emulateMedia() 和 browser.newContext(),允许模拟prefers-contrast媒体特性。 - 新的选项 failOnStatusCode 会使通过 APIRequestContext 发出的所有 fetch 请求在响应状态码不是 2xx 或 3xx 时抛出异常。
- 断言 expect(page).toHaveURL() 现在支持谓词。
浏览器版本
🌐 Browser Versions
- Chromium 134.0.6998.35
- Mozilla Firefox 135.0
- WebKit 18.4
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- Google Chrome 133
- Microsoft Edge 133
1.50 版本
🌐 Version 1.50
测试运行器
🌐 Test runner
-
新的选项 timeout 允许为单个测试步骤指定最大运行时间。超时的步骤将导致测试执行失败。
test('some test', async ({ page }) => {
await test.step('a step', async () => {
// This step can time out separately from the test
}, { timeout: 1000 });
}); -
新方法 test.step.skip() 用于禁用测试步骤的执行。
test('some test', async ({ page }) => {
await test.step('before running step', async () => {
// Normal step
});
await test.step.skip('not yet ready', async () => {
// This step is skipped
});
await test.step('after running step', async () => {
// This step still runs even though the previous one was skipped
});
}); -
扩展了 expect(locator).toMatchAriaSnapshot(),以允许将 aria 快照存储在单独的 YAML 文件中。
-
新增方法 expect(locator).toHaveAccessibleErrorMessage(),用于断言 Locator 指向具有给定 aria errormessage 的元素。
-
选项 testConfig.updateSnapshots 添加了配置枚举
changed。changed仅更新已更改的快照,而all现在会更新所有快照,无论是否有任何差异。 -
新选项testConfig.updateSourceMethod定义了在配置testConfig.updateSnapshots时源码的更新方式。除了现有的创建补丁文件的patch模式外,还新增了将更改直接写入源码的overwrite和3-way模式。
npx playwright test --update-snapshots=changed --update-source-method=3way -
选项testConfig.webServer 添加了一个
gracefulShutdown字段,用于指定除默认SIGKILL外的进程终止信号。 -
从报告 API 中公开了 testStep.attachments,以便检索该步骤创建的所有附件。
-
testConfig.expect 配置中
toHaveScreenshot和toMatchAriaSnapshot断言的新选项pathTemplate。
UI 更新
🌐 UI updates
- 更新了默认 HTML 报告器以改进附件的显示。
- Codegen 中的新按钮用于选择元素以生成 aria 快照。
- 其他详细信息(例如按下的键)现在与跟踪中的操作 API 调用一起显示。
- 在跟踪中显示
canvas内容容易出错。默认情况下已禁用显示,可以通过Display canvas content用户界面设置启用。 Call和Network面板现在显示额外的时间信息。
重点
🌐 Breaking
- expect(locator).toBeEditable() 和 locator.isEditable() 现在会在目标元素不是
<input>、<select>或其他可编辑元素时抛出错误。 - 选项 testConfig.updateSnapshots 现在在设置为
all时会更新所有快照,而不仅仅是失败/更改的快照。使用新的枚举changed可保持旧功能,仅更新更改的快照。
浏览器版本
🌐 Browser Versions
- Chromium 133.0.6943.16
- Mozilla Firefox 134.0
- WebKit 18.2
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- Google Chrome 132
- Microsoft Edge 132
1.49 版本
🌐 Version 1.49
Aria 快照
🌐 Aria snapshots
新的断言 expect(locator).toMatchAriaSnapshot() 通过与预期的无障碍树(以 YAML 表示)比较来验证页面结构。
🌐 New assertion expect(locator).toMatchAriaSnapshot() verifies page structure by comparing to an expected accessibility tree, represented as YAML.
await page.goto('https://playwright.nodejs.cn');
await expect(page.locator('body')).toMatchAriaSnapshot(`
- banner:
- heading /Playwright enables reliable/ [level=1]
- link "Get started"
- link "Star microsoft/playwright on GitHub"
- main:
- img "Browsers (Chromium, Firefox, WebKit)"
- heading "Any browser • Any platform • One API"
`);
你可以使用 Test Generator 生成此断言,并使用 --update-snapshots 命令行标志更新预期快照。
🌐 You can generate this assertion with Test Generator and update the expected snapshot with --update-snapshots command line flag.
在ARIA 快照指南中了解更多。
🌐 Learn more in the aria snapshots guide.
测试运行器
🌐 Test runner
- 新选项 testConfig.tsconfig 允许指定单个
tsconfig用于所有测试。 - 新方法 test.fail.only() 用于专注于失败的测试。
- 选项 testConfig.globalSetup 和 testConfig.globalTeardown 现在支持多个设置/拆解操作。
- testOptions.screenshot的新值为
'on-first-failure'。 - 在HTML报告中增加了“上一”和“下一”按钮,以便快速切换测试用例。
- 新属性 testInfoError.cause 和 testError.cause 镜像
Error.cause。
最新消息:chrome 和 msedge 通道切换到新的无头模式
🌐 Breaking: chrome and msedge channels switch to new headless mode
如果你在 playwright.config.ts 中使用以下渠道之一,这一更改将会影响你:
🌐 This change affects you if you're using one of the following channels in your playwright.config.ts:
chrome、chrome-dev、chrome-beta或chrome-canarymsedge、msedge-dev、msedge-beta或msedge-canary
我需要做什么?
🌐 What do I need to do?
在更新到 Playwright v1.49 后,运行你的测试套件。如果测试仍然通过,那么你就可以继续使用。如果没有,你可能需要更新你的快照,并调整一些关于 PDF 查看器和扩展的测试代码。更多详情请参见 issue #33566。
🌐 After updating to Playwright v1.49, run your test suite. If it still passes, you're good to go. If not, you will probably need to update your snapshots, and adapt some of your test code around PDF viewers and extensions. See issue #33566 for more details.
其他重大更改
🌐 Other breaking changes
- Ubuntu 20.04 和 Debian 11 的 WebKit 将不再有更新。我们建议将操作系统升级到更高版本。
- 软件包
@playwright/experimental-ct-vue2将不再更新。 - 软件包
@playwright/experimental-ct-solid将不再更新。
尝试新的 Chromium 无头
🌐 Try new Chromium headless
你可以通过使用 'chromium' 通道来选择新的无头模式。正如官方 Chrome 文档所述:
🌐 You can opt into the new headless mode by using 'chromium' channel. As official Chrome documentation puts it:
另一方面,新的无头模式是真正的 Chrome 浏览器,因此更真实、可靠,并提供更多功能。这使得它更适合进行高精度的端到端网络应用测试或浏览器扩展测试。
请参见 issue #33566 了解你可能遇到的断裂问题列表以及有关无头 Chromium 的更多详细信息。如果在选择加入后遇到任何问题,请提交问题报告。
🌐 See issue #33566 for the list of possible breakages you could encounter and more details on Chromium headless. Please file an issue if you see any problems after opting in.
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'], channel: 'chromium' },
},
],
});
杂项
🌐 Miscellaneous
- 快照中的
<canvas>元素现在会显示预览。 - 新方法 tracing.group() 用于在跟踪中直观地分组操作。
- Playwright docker 镜像从 Node.js v20 切换到 Node.js v22 LTS。
浏览器版本
🌐 Browser Versions
- Chromium 131.0.6778.33
- Mozilla Firefox 132.0
- WebKit 18.2
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- Google Chrome 130
- Microsoft Edge 130
1.48 版本
🌐 Version 1.48
WebSocket 路由
🌐 WebSocket routing
新的方法 page.routeWebSocket() 和 browserContext.routeWebSocket() 允许拦截、修改和模拟页面中发起的 WebSocket 连接。下面是一个简单的示例,通过对 "request" 响应 "response" 来模拟 WebSocket 通信。
🌐 New methods page.routeWebSocket() and browserContext.routeWebSocket() allow to intercept, modify and mock WebSocket connections initiated in the page. Below is a simple example that mocks WebSocket communication by responding to a "request" with a "response".
await page.routeWebSocket('/ws', ws => {
ws.onMessage(message => {
if (message === 'request')
ws.send('response');
});
});
查看更多详情,请参阅 WebSocketRoute。
🌐 See WebSocketRoute for more details.
UI 更新
🌐 UI updates
- HTML 报告中为注释和测试位置新增了“复制”按钮。
- 像 route.fulfill() 这样的路由方法调用不再显示在报告和跟踪查看器中。你可以在网络选项卡中查看哪些网络请求被路由了。
- 网络面板中的请求新增了“复制为 cURL”和“复制为 fetch”按钮。
杂项
🌐 Miscellaneous
- 选项 form 和类似选项现在支持 FormData。
- 新方法 page.requestGC() 可能有助于检测内存泄漏。
- 新选项 location 用于传递自定义步骤位置。
- APIRequestContext 发出的请求现在会在 HAR 中记录详细的时间和安全信息。
浏览器版本
🌐 Browser Versions
- Chromium 130.0.6723.19
- Mozilla Firefox 130.0
- WebKit 18.0
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- Google Chrome 129
- Microsoft Edge 129
1.47 版本
🌐 Version 1.47
网络选项卡改进
🌐 Network Tab improvements
UI 模式和跟踪查看器中的“网络”选项卡有几个不错的改进:
🌐 The Network tab in the UI mode and trace viewer has several nice improvements:
- 按资源类型和 URL 过滤
- 更好地显示查询字符串参数
- 字体资源预览
--tsconfig 命令行选项
🌐 --tsconfig CLI option
默认情况下,Playwright 会使用启发式方法查找每个导入文件的最近 tsconfig。现在,你可以在命令行中指定一个单独的 tsconfig 文件,Playwright 将对所有导入文件使用它,而不仅仅是测试文件:
🌐 By default, Playwright will look up the closest tsconfig for each imported file using a heuristic. You can now specify a single tsconfig file in the command line, and Playwright will use it for all imported files, not only test files:
# Pass a specific tsconfig
npx playwright test --tsconfig tsconfig.test.json
APIRequestContext 现在接受 URLSearchParams 和 string 作为查询参数
🌐 APIRequestContext] now accepts [URLSearchParams and string as query parameters
你现在可以将 URLSearchParams 和 string 作为查询参数传递给 APIRequestContext:
🌐 You can now pass URLSearchParams and string as query parameters to APIRequestContext:
test('query params', async ({ request }) => {
const searchParams = new URLSearchParams();
searchParams.set('userId', 1);
const response = await request.get(
'https://jsonplaceholder.typicode.com/posts',
{
params: searchParams // or as a string: 'userId=1'
}
);
// ...
});
杂项
🌐 Miscellaneous
mcr.microsoft.com/playwright:v1.47.0现在基于 Ubuntu 24.04 Noble 提供 Playwright 镜像。要使用基于 22.04 jammy 的镜像,请改用mcr.microsoft.com/playwright:v1.47.0-jammy。- 新的选项 behavior、behavior 和 behavior 用于等待正在进行的监听器完成。
- TLS 客户端证书现在可以通过内存传递,只需将 clientCertificates.cert 和 clientCertificates.key 作为缓冲区传递,而不是文件路径。
- 现在,可以在 HTML 报告中新标签页中打开内容类型为
text/html的附件。这对于在 Playwright 测试报告中包含第三方报告或其他 HTML 内容并与团队共享非常有用。 - [locator.selectOption()] 中的 noWaitAfter 选项已被弃用。
- 我们在 GitHub Actions
macos-13上看到关于 Webkit 中 WebGL 异常行为的报告。我们建议将 GitHub Actions 升级到macos-14。
浏览器版本
🌐 Browser Versions
- Chromium 129.0.6668.29
- Mozilla Firefox 130.0
- WebKit 18.0
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- Google Chrome 128
- Microsoft Edge 128
1.46 版本
🌐 Version 1.46
TLS 客户端证书
🌐 TLS Client Certificates
Playwright 现在允许你提供客户端证书,以便服务器可以验证它们,如 TLS 客户端身份验证所指定。
🌐 Playwright now allows you to supply client-side certificates, so that server can verify them, as specified by TLS Client Authentication.
以下代码片段为 https://example.com 设置了一个客户端证书:
🌐 The following snippet sets up a client certificate for https://example.com:
import { defineConfig } from '@playwright/test';
export default defineConfig({
// ...
use: {
clientCertificates: [{
origin: 'https://example.com',
certPath: './cert.pem',
keyPath: './key.pem',
passphrase: 'mysecretpassword',
}],
},
// ...
});
你还可以将客户端证书提供给特定的test项目,或作为browser.newContext()和apiRequest.newContext()的参数。
🌐 You can also provide client certificates to a particular test project or as a parameter of browser.newContext() and apiRequest.newContext().
--only-changed 命令行选项
🌐 --only-changed cli option
新的 CLI 选项 --only-changed 只会运行自上一次 git 提交以来已更改的测试文件,或指定 git “引用”中的更改文件。它还会运行所有导入了任何已更改文件的测试文件。
🌐 New CLI option --only-changed will only run test files that have been changed since the last git commit or from a specific git "ref". This will also run all test files that import any changed files.
# Only run test files with uncommitted changes
npx playwright test --only-changed
# Only run test files changed relative to the "main" branch
npx playwright test --only-changed=main
组件测试:新的 router 夹具
🌐 Component Testing: New router fixture
此版本引入了一个实验性的 router 夹具,用于在组件测试中拦截和处理网络请求。有两种使用路由夹具的方法:
🌐 This release introduces an experimental router fixture to intercept and handle network requests in component testing. There are two ways to use the router fixture:
- 调用
router.route(url, handler),其行为类似于 page.route()。 - 调用
router.use(handlers)并将 MSW 库 的请求处理程序传递给它。
以下是在测试中重用现有 MSW 处理程序的示例。
🌐 Here is an example of reusing your existing MSW handlers in the test.
import { handlers } from '@src/mocks/handlers';
test.beforeEach(async ({ router }) => {
// install common handlers before each test
await router.use(...handlers);
});
test('example test', async ({ mount }) => {
// test as usual, your handlers are active
// ...
});
此夹具仅在组件测试中可用。
🌐 This fixture is only available in component tests.
UI 模式/跟踪查看器更新
🌐 UI Mode / Trace Viewer Updates
- 测试注释现在显示在 UI 模式下。
- 文本附件的内容现在在附件窗格中以内联方式渲染。
- 新增设置以显示/隐藏路由操作,如 route.continue()。
- 请求方法和状态显示在网络详细信息选项卡中。
- 新按钮用于将源文件位置复制到剪贴板。
- 元数据窗格现在显示
baseURL。
杂项
🌐 Miscellaneous
- apiRequestContext.fetch() 中新增
maxRetries选项,可在遇到ECONNRESET网络错误时重试。 - 新增选项可以隐藏夹具,以在测试报告和错误消息中将夹具暴露最小化。
- 新增选项,可提供一个 自定义夹具标题,用于测试报告和错误信息中。
浏览器版本
🌐 Browser Versions
- Chromium 128.0.6613.18
- Mozilla Firefox 128.0
- WebKit 18.0
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- Google Chrome 127
- Microsoft Edge 127
1.45 版本
🌐 Version 1.45
时钟
🌐 Clock
使用新的 Clock API 可以在测试中操作和控制时间,以验证与时间相关的行为。该 API 涵盖了许多常见的场景,包括:
🌐 Utilizing the new Clock API allows to manipulate and control time within tests to verify time-related behavior. This API covers many common scenarios, including:
- 使用预定义时间进行测试;
- 保持一致的时间和计时器;
- 监控不活动;
- 手动计时。
// Initialize clock and let the page load naturally.
await page.clock.install({ time: new Date('2024-02-02T08:00:00') });
await page.goto('http://localhost:3333');
// Pretend that the user closed the laptop lid and opened it again at 10am,
// Pause the time once reached that point.
await page.clock.pauseAt(new Date('2024-02-02T10:00:00'));
// Assert the page state.
await expect(page.getByTestId('current-time')).toHaveText('2/2/2024, 10:00:00 AM');
// Close the laptop lid again and open it at 10:30am.
await page.clock.fastForward('30:00');
await expect(page.getByTestId('current-time')).toHaveText('2/2/2024, 10:30:00 AM');
有关更多详情,请参见时钟指南。
🌐 See the clock guide for more details.
测试运行器
🌐 Test runner
-
新的命令行选项
--fail-on-flaky-tests可在出现任何不稳定的测试时将退出代码设置为1。请注意,默认情况下,当所有失败的测试在重试后恢复时,测试运行器会以代码0退出。使用此选项时,在这种情况下测试运行将会失败。 -
新的环境变量
PLAYWRIGHT_FORCE_TTY控制内置的list、line和dot报告器是否假定为活跃终端。例如,当你的 CI 环境不能很好地处理 ANSI 控制序列时,这可能有助于禁用 tty 行为。或者,即使存在活跃终端,如果你计划对输出进行后处理并处理控制序列,也可以启用 tty 行为。# Avoid TTY features that output ANSI control sequences
PLAYWRIGHT_FORCE_TTY=0 npx playwright test
# Enable TTY features, assuming a terminal width 80
PLAYWRIGHT_FORCE_TTY=80 npx playwright test -
新的选项 testConfig.respectGitIgnore 和 testProject.respectGitIgnore 用于控制在搜索测试时是否排除匹配
.gitignore模式的文件。 -
新资源“timeout”现已提供自定义期待匹配器使用。该属性考虑了“playwright.config.ts”和“expect.configure()”。
import { expect as baseExpect } from '@playwright/test';
export const expect = baseExpect.extend({
async toHaveAmount(locator: Locator, expected: number, options?: { timeout?: number }) {
// When no timeout option is specified, use the config timeout.
const timeout = options?.timeout ?? this.timeout;
// ... implement the assertion ...
},
});
杂项
🌐 Miscellaneous
-
方法 locator.setInputFiles() 现在支持为
<input type=file webkitdirectory>元素上传整个目录。await page.getByLabel('Upload directory').setInputFiles(path.join(__dirname, 'mydir')); -
像 locator.click() 或 locator.press() 这样的多种方法现在支持
ControlOrMeta修饰键。这个键在 macOS 上对应Meta,在 Windows 和 Linux 上对应Control。// Press the common keyboard shortcut Control+S or Meta+S to trigger a "Save" operation.
await page.keyboard.press('ControlOrMeta+S'); -
apiRequest.newContext() 中的新属性
httpCredentials.send,允许始终发送Authorization头,或者仅在响应401 Unauthorized时发送该头。 -
apiRequestContext.dispose() 中的新选项
reason,将在因上下文销毁而中断的正在进行的操作的错误信息中包含。 -
browserType.launchServer() 中的新选项
host允许在特定地址上接受 websocket 连接,而不是未指定的0.0.0.0。 -
Playwright 现在支持 Ubuntu 24.04 上的 Chromium、Firefox 和 WebKit。
-
v1.45 是最后一个为 macOS 12 Monterey 提供 WebKit 更新的版本。请更新 macOS 以继续使用最新的 WebKit。
浏览器版本
🌐 Browser Versions
- Chromium 127.0.6533.5
- Mozilla Firefox 127.0
- 网络工具包 17.4
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- Google Chrome 126
- Microsoft Edge 126
1.44 版本
🌐 Version 1.44
新 API
🌐 New APIs
无障碍声明
-
expect(locator).toHaveAccessibleName() 检查该元素是否具有指定的可访问名称:
const locator = page.getByRole('button');
await expect(locator).toHaveAccessibleName('Submit'); -
expect(locator).toHaveAccessibleDescription() 检查该元素是否具有指定的可访问描述:
const locator = page.getByRole('button');
await expect(locator).toHaveAccessibleDescription('Upload a photo'); -
expect(locator).toHaveRole() 检查元素是否具有指定的 ARIA 角色:
const locator = page.getByTestId('save-button');
await expect(locator).toHaveRole('button');
定位器处理程序
- 在执行通过 page.addLocatorHandler() 添加的处理程序后,Playwright 现在将等待直到触发该处理程序的覆盖层不再可见。你可以使用新的
noWaitAfter选项选择不启用此行为。 - 你可以在 page.addLocatorHandler() 中使用新的
times选项来指定处理程序应运行的最大次数。 - page.addLocatorHandler() 中的处理程序现在接受定位器作为参数。
- 新增 page.removeLocatorHandler() 方法,用于移除之前添加的定位器处理程序。
const locator = page.getByText('This interstitial covers the button');
await page.addLocatorHandler(locator, async overlay => {
await overlay.locator('#close').click();
}, { times: 3, noWaitAfter: true });
// Run your tests that can be interrupted by the overlay.
// ...
await page.removeLocatorHandler(locator);
其他选项
-
apiRequestContext.fetch()中的multipart选项现在接受FormData并支持具有相同名称的重复字段。const formData = new FormData();
formData.append('file', new File(['let x = 2024;'], 'f1.js', { type: 'text/javascript' }));
formData.append('file', new File(['hello'], 'f2.txt', { type: 'text/plain' }));
context.request.post('https://example.com/uploadFiles', {
multipart: formData
}); -
expect(callback).toPass({ intervals })现在可以通过[testConfig.expect](/api/class-testconfig.mdx#test-config-expect)中的expect.toPass.intervals选项全局配置,或在[testProject.expect](/api/class-testproject.mdx#test-project-expect)中按项目配置。 -
expect(page).toHaveURL(url)now supportsignoreCaseoption. -
testProject.ignoreSnapshots 允许为每个项目配置是否跳过截图预期。
报告器 API
- 新方法 suite.entries() 按声明顺序返回子测试套件和测试用例。可以使用 suite.type 和 testCase.type 来区分列表中的测试用例和测试套件。
- Blob 报告器现在允许使用单个选项
outputFile来覆盖报告文件路径。相同的选项也可以通过PLAYWRIGHT_BLOB_OUTPUT_FILE环境变量指定,这在 CI/CD 上可能更方便。 - JUnit 报告器现在支持
includeProjectInTestName选项。
命令行
-
--last-failedCLI 选项用于仅运行上一次运行中失败的测试。首先运行所有测试:
$ npx playwright test
Running 103 tests using 5 workers
...
2 failed
[chromium] › my-test.spec.ts:8:5 › two ─────────────────────────────────────────────────────────
[chromium] › my-test.spec.ts:13:5 › three ──────────────────────────────────────────────────────
101 passed (30.0s)现在修复未通过的测试,并使用
--last-failed选项再次运行 Playwright:$ npx playwright test --last-failed
Running 2 tests using 2 workers
2 passed (1.2s)
浏览器版本
🌐 Browser Versions
- Chromium 125.0.6422.14
- Mozilla Firefox 125.0.1
- 网络工具包 17.4
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- Google Chrome 124
- Microsoft Edge 124
1.43 版本
🌐 Version 1.43
新 API
🌐 New APIs
-
方法 browserContext.clearCookies() 现在支持过滤器,可仅删除某些 cookie。
// Clear all cookies.
await context.clearCookies();
// New: clear cookies with a particular name.
await context.clearCookies({ name: 'session-id' });
// New: clear cookies for a particular domain.
await context.clearCookies({ domain: 'my-origin.com' }); -
[testOptions.trace] 的新模式
retain-on-first-failure。在此模式下,每个测试的第一次运行会记录跟踪,但重试时不会记录。测试运行失败时,跟踪文件会保留,否则将被删除。import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
trace: 'retain-on-first-failure',
},
}); -
新属性 testInfo.tags 在测试执行过程中显示测试标签。
test('example', async ({ page }) => {
console.log(test.info().tags);
}); -
新方法 locator.contentFrame() 将 Locator 对象转换为 FrameLocator。当你已经在某处获得了一个 Locator 对象,并且希望随后与框架内的内容进行交互时,这会非常有用。
const locator = page.locator('iframe[name="embedded"]');
// ...
const frameLocator = locator.contentFrame();
await frameLocator.getByRole('button').click(); -
新方法 frameLocator.owner() 将 FrameLocator 对象转换为 Locator。当你在某处获得一个 FrameLocator 对象,并且之后希望与
iframe元素进行交互时,这会很有用。const frameLocator = page.frameLocator('iframe[name="embedded"]');
// ...
const locator = frameLocator.owner();
await expect(locator).toBeVisible();
用户界面模式更新
🌐 UI Mode Updates
- 查看测试列表中的标签。
- 通过输入
@fast或点击标签本身来筛选标签。 - 新的快捷键:
- 按“F5”运行测试。
- 按 “Shift F5” 停止运行测试。
- 按 "Ctrl + `" 切换测试输出。
浏览器版本
🌐 Browser Versions
- Chromium 124.0.6367.8
- 火狐浏览器 124.0
- 网络工具包 17.4
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- 谷歌浏览器 123
- 微软边缘 123
1.42 版本
🌐 Version 1.42
新 API
🌐 New APIs
- 新方法 page.addLocatorHandler() 注册一个回调函数,当指定元素可见时会调用它,并可能阻塞 Playwright 的操作。回调函数可以移除覆盖层。下面是一个示例,当 cookie 对话框出现时关闭它:
// Setup the handler.
await page.addLocatorHandler(
page.getByRole('heading', { name: 'Hej! You are in control of your cookies.' }),
async () => {
await page.getByRole('button', { name: 'Accept all' }).click();
});
// Write the test as usual.
await page.goto('https://www.ikea.com/');
await page.getByRole('link', { name: 'Collection of blue and white' }).click();
await expect(page.getByRole('heading', { name: 'Light and easy' })).toBeVisible();
expect(callback).toPass()超时现在可以通过expect.toPass.timeout选项在 全局 或在 项目配置 中进行配置- 当 Electron 主进程调用控制台(console)API 方法时,会触发 electronApplication.on('console') 事件。
electronApp.on('console', async msg => {
const values = [];
for (const arg of msg.args())
values.push(await arg.jsonValue());
console.log(...values);
});
await electronApp.evaluate(() => console.log('hello', 5, { foo: 'bar' }));
- 用于向测试添加标签的新语法(测试标题中的 @ 符号仍然受支持):
test('test customer login', {
tag: ['@fast', '@login'],
}, async ({ page }) => {
// ...
});
使用 --grep 命令行选项仅运行带有特定标签的测试。
🌐 Use --grep command line option to run only tests with certain tags.
npx playwright test --grep @fast
--project命令行 标志 现在支持 '*' 通配符:
npx playwright test --project='*mobile*'
test('test full report', {
annotation: [
{ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/23180' },
{ type: 'docs', description: 'https://playwright.nodejs.cn/docs/test-annotations#tag-tests' },
],
}, async ({ page }) => {
// ...
});
- page.pdf() accepts two new options
taggedandoutline.
公告
🌐 Announcements
- ⚠️ Ubuntu 18 已不再受支持。
浏览器版本
🌐 Browser Versions
- Chromium 123.0.6312.4
- 火狐浏览器 123.0
- 网络工具包 17.4
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- 谷歌浏览器 122
- 微软边缘 123
1.41 版本
🌐 Version 1.41
新 API
🌐 New APIs
- 新方法 page.unrouteAll() 会移除所有由 page.route() 和 page.routeFromHAR() 注册的路由。可以选择等待正在进行的路由完成,或忽略它们产生的任何错误。
- 新方法 browserContext.unrouteAll() 会移除所有由 browserContext.route() 和 browserContext.routeFromHAR() 注册的路由。可选地,允许等待正在进行的路由完成,或忽略它们的任何错误。
- 在 page.screenshot() 中新增选项 style 和在 locator.screenshot() 中新增选项 style,可在截图前向页面添加自定义 CSS。
- 为方法 expect(page).toHaveScreenshot() 和 expect(locator).toHaveScreenshot() 添加了新选项
stylePath,可在截图时应用自定义样式表。 - Blob reporter 新增
fileName选项,用于指定要创建的报告名称。
浏览器版本
🌐 Browser Versions
- Chromium 121.0.6167.57
- 火狐浏览器 121.0
- 网络工具包 17.4
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- 谷歌浏览器 120
- 微软 Edge 120
1.40 版本
🌐 Version 1.40
测试生成器更新
🌐 Test Generator Update
生成断言的新工具:
🌐 New tools to generate assertions:
- "“断言可见性”工具会生成 expect(locator).toBeVisible()。"
- “断言值”工具会生成 expect(locator).toHaveValue()。
- "Assert text" 工具会生成 expect(locator).toContainText()。
以下是带有断言的生成测试的示例:
🌐 Here is an example of a generated test with assertions:
import { test, expect } from '@playwright/test';
test('test', async ({ page }) => {
await page.goto('https://playwright.nodejs.cn/');
await page.getByRole('link', { name: 'Get started' }).click();
await expect(page.getByLabel('Breadcrumbs').getByRole('list')).toContainText('Installation');
await expect(page.getByLabel('Search')).toBeVisible();
await page.getByLabel('Search').click();
await page.getByPlaceholder('Search docs').fill('locator');
await expect(page.getByPlaceholder('Search docs')).toHaveValue('locator');
});
新 API
🌐 New APIs
- 在 page.close() 中的选项 reason、在 browserContext.close() 中的 reason 以及在 browser.close() 中的 reason。关闭原因会报告给所有因关闭而中断的操作。
- [browserType.launchPersistentContext()] 中的选项 firefoxUserPrefs。
其他变更
🌐 Other Changes
- 方法 download.path() 和 download.createReadStream() 在下载失败或取消时会抛出错误。
- Playwright Docker 镜像 现在包含 Node.js v20。
浏览器版本
🌐 Browser Versions
- Chromium 120.0.6099.28
- 火狐浏览器 119.0
- 网络工具包 17.4
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- 谷歌浏览器 119
- 微软 Edge 119
1.39 版本
🌐 Version 1.39
根据你的期望添加自定义匹配器
🌐 Add custom matchers to your expect
你可以通过提供自定义匹配器来扩展 Playwright 的断言。这些匹配器将在 expect 对象上可用。
🌐 You can extend Playwright assertions by providing custom matchers. These matchers will be available on the expect object.
import { expect as baseExpect } from '@playwright/test';
export const expect = baseExpect.extend({
async toHaveAmount(locator: Locator, expected: number, options?: { timeout?: number }) {
// ... see documentation for how to write matchers.
},
});
test('pass', async ({ page }) => {
await expect(page.getByTestId('cart')).toHaveAmount(5);
});
请参阅文档 查看完整示例。
🌐 See the documentation for a full example.
合并测试夹具
🌐 Merge test fixtures
你现在可以合并来自多个文件或模块的测试装置:
🌐 You can now merge test fixtures from multiple files or modules:
import { mergeTests } from '@playwright/test';
import { test as dbTest } from 'database-test-utils';
import { test as a11yTest } from 'a11y-test-utils';
export const test = mergeTests(dbTest, a11yTest);
import { test } from './fixtures';
test('passes', async ({ database, page, a11y }) => {
// use database and a11y fixtures.
});
合并自定义期望匹配器
🌐 Merge custom expect matchers
你现在可以合并来自多个文件或模块的自定义期望匹配器:
🌐 You can now merge custom expect matchers from multiple files or modules:
import { mergeTests, mergeExpects } from '@playwright/test';
import { test as dbTest, expect as dbExpect } from 'database-test-utils';
import { test as a11yTest, expect as a11yExpect } from 'a11y-test-utils';
export const test = mergeTests(dbTest, a11yTest);
export const expect = mergeExpects(dbExpect, a11yExpect);
import { test, expect } from './fixtures';
test('passes', async ({ page, database }) => {
await expect(database).toHaveDatabaseUser('admin');
await expect(page).toPassA11yAudit();
});
隐藏实现细节:盒子测试步骤
🌐 Hide implementation details: box test steps
你可以将 test.step() 标记为“boxed”,这样其中的错误会指向步骤调用的位置。
🌐 You can mark a test.step() as "boxed" so that errors inside it point to the step call site.
async function login(page) {
await test.step('login', async () => {
// ...
}, { box: true }); // Note the "box" option here.
}
Error: Timed out 5000ms waiting for expect(locator).toBeVisible()
... error details omitted ...
14 | await page.goto('https://github.com/login');
> 15 | await login(page);
| ^
16 | });
请参阅 test.step() 文档以获取完整示例。
🌐 See test.step() documentation for a full example.
新 API
🌐 New APIs
浏览器版本
🌐 Browser Versions
- Chromium 119.0.6045.9
- 火狐浏览器 118.0.1
- 网络工具包 17.4
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- 谷歌浏览器 118
- 微软 Edge 118
1.38 版本
🌐 Version 1.38
用户界面模式更新
🌐 UI Mode Updates
- 放大时间范围。
- 网络面板重新设计。
新 API
🌐 New APIs
- browserContext.on('weberror')
- locator.pressSequentially()
- reporter.onEnd() 现在报告
startTime和总运行时间duration。
弃用
🌐 Deprecations
- 以下方法已被弃用:page.type()、frame.type()、locator.type() 和 elementHandle.type()。请改用 locator.fill(),速度更快。仅当页面上有特殊的键盘处理且需要逐个按键时,才使用 locator.pressSequentially()。
重大更改:Playwright 不再自动下载浏览器
🌐 Breaking Changes: Playwright no longer downloads browsers automatically
注意:如果你使用的是
@playwright/test包,此更改不会影响你。
Playwright 建议使用 @playwright/test 包并通过 npx playwright install 命令下载浏览器。如果你遵循这个建议,对你来说没有任何变化。
🌐 Playwright recommends to use @playwright/test package and download browsers via npx playwright install command. If you are following this recommendation, nothing has changed for you.
然而,直到 v1.38 版本,安装 playwright 软件包而不是 @playwright/test 会自动下载浏览器。现在情况已经不再如此,我们建议通过 npx playwright install 命令显式下载浏览器。
🌐 However, up to v1.38, installing the playwright package instead of @playwright/test did automatically download browsers. This is no longer the case, and we recommend to explicitly download browsers via npx playwright install command.
v1.37 及更早版本
playwright 包在 npm install 期间正在下载浏览器,而 @playwright/test 则没有。
v1.38 及以后
playwright 和 @playwright/test 软件包在 npm install 期间不会下载浏览器。
推荐迁移
在 npm install 之后运行 npx playwright install 来下载浏览器。例如,在你的 CI 配置中:
🌐 Run npx playwright install to download browsers after npm install. For example, in your CI configuration:
- run: npm ci
- run: npx playwright install --with-deps
替代迁移选项 - 不推荐
将 @playwright/browser-chromium、@playwright/browser-firefox 和 @playwright/browser-webkit 添加为依赖。这些包会在 npm install 期间下载相应的浏览器。确保所有 Playwright 包的版本保持同步:
🌐 Add @playwright/browser-chromium, @playwright/browser-firefox and @playwright/browser-webkit as a dependency. These packages download respective browsers during npm install. Make sure you keep the version of all playwright packages in sync:
// package.json
{
"devDependencies": {
"playwright": "1.38.0",
"@playwright/browser-chromium": "1.38.0",
"@playwright/browser-firefox": "1.38.0",
"@playwright/browser-webkit": "1.38.0"
}
}
浏览器版本
🌐 Browser Versions
- Chromium 117.0.5938.62
- 火狐浏览器 117.0
- 网络工具包 17.0
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- 谷歌浏览器 116
- 微软 Edge 116
1.37 版本
🌐 Version 1.37
新的 npx playwright merge-reports 工具
🌐 New npx playwright merge-reports tool
如果你在多个分片上运行测试,现在可以使用新的 merge-reports 命令行工具将所有报告合并为单个 HTML 报告(或任何其他报告)。
🌐 If you run tests on multiple shards, you can now merge all reports in a single HTML report (or any other report) using the new merge-reports CLI tool.
使用 merge-reports 工具需要以下步骤:
🌐 Using merge-reports tool requires the following steps:
-
在 CI 上运行时向配置中添加新的“blob”报告器:
playwright.config.tsexport default defineConfig({
testDir: './tests',
reporter: process.env.CI ? 'blob' : 'html',
});“blob” 报告器会生成包含有关测试运行的所有信息的 “.zip” 文件。
-
将所有“blob”报告复制到一个共享位置并运行
npx playwright merge-reports:
npx playwright merge-reports --reporter html ./all-blob-reports
在我们的文档中阅读更多内容。
🌐 Read more in our documentation.
📚 Debian 12 Bookworm 支持
🌐 📚 Debian 12 Bookworm Support
Playwright 现在支持在 x86_64 和 arm64 上的 Debian 12 Bookworm,用于 Chromium、Firefox 和 WebKit。如果你遇到任何问题,请告知我们!
🌐 Playwright now supports Debian 12 Bookworm on both x86_64 and arm64 for Chromium, Firefox and WebKit. Let us know if you encounter any issues!
Linux 支持如下所示:
🌐 Linux support looks like this:
| Ubuntu 20.04 | Ubuntu 22.04 | Debian 11 | Debian 12 | |
|---|---|---|---|---|
| Chromium | ✅ | ✅ | ✅ | ✅ |
| WebKit | ✅ | ✅ | ✅ | ✅ |
| Firefox | ✅ | ✅ | ✅ | ✅ |
用户界面模式更新
🌐 UI Mode Updates
- UI 模式现在会遵循项目依赖。你可以通过在项目列表中勾选或取消勾选来控制遵循哪些依赖。
- 测试的控制台日志现在显示在“控制台”选项卡中。
浏览器版本
🌐 Browser Versions
- Chromium 116.0.5845.82
- 火狐浏览器 115.0
- 网络工具包 17.0
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- 谷歌浏览器 115
- 微软 Edge 115
1.36 版本
🌐 Version 1.36
🏝️ 夏季维护更新。
浏览器版本
🌐 Browser Versions
- Chromium 115.0.5790.75
- 火狐浏览器 115.0
- 网络工具包 17.0
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- 谷歌浏览器 114
- 微软 Edge 114
1.35 版本
🌐 Version 1.35
高亮
🌐 Highlights
-
现在,VSCode Playwright 扩展通过一个新的“显示跟踪查看器”按钮提供了 UI 模式:
-
UI 模式和跟踪查看器会标记通过 page.route() 和 browserContext.route() 处理的网络请求,以及通过 API 测试 发出的请求:
-
为方法 page.screenshot()、locator.screenshot()、expect(page).toHaveScreenshot() 和 expect(locator).toHaveScreenshot() 添加新选项
maskColor,用于更改默认遮罩颜色:await page.goto('https://playwright.nodejs.cn');
await expect(page).toHaveScreenshot({
mask: [page.locator('img')],
maskColor: '#00FF00', // green
}); -
新的
uninstallCLI 命令用于卸载浏览器二进制文件:$ npx playwright uninstall # remove browsers installed by this installation
$ npx playwright uninstall --all # remove all ever-install Playwright browsers -
UI 模式和跟踪查看器现在都可以在浏览器选项卡中打开:
$ npx playwright test --ui-port 0 # open UI mode in a tab on a random port
$ npx playwright show-trace --port 0 # open trace viewer in tab on a random port
⚠️ 重大更改
🌐 ⚠️ Breaking changes
-
playwright-core二进制文件已从playwright重命名为playwright-core。因此,如果你使用playwright-coreCLI,请确保更新名称:$ npx playwright-core install # the new way to install browsers when using playwright-core此更改不影响
@playwright/test和playwright软件包的用户。
浏览器版本
🌐 Browser Versions
- Chromium 115.0.5790.13
- 火狐浏览器 113.0
- 网络工具包 16.4
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- 谷歌浏览器 114
- 微软 Edge 114
1.34 版本
🌐 Version 1.34
高亮
🌐 Highlights
-
UI 模式现在显示步骤、夹具和附件:
-
新属性 [testProject.teardown](/api/class-testproject.mdx#test-project-teardown)用来指定一个项目,该项目需要在此之后运行,且所有依赖目都已完成。拆除有助于清理本项目获得的资源。
一个常见的模式是具有相应
teardown的setup依赖:playwright.config.tsimport { defineConfig } from '@playwright/test';
export default defineConfig({
projects: [
{
name: 'setup',
testMatch: /global.setup\.ts/,
teardown: 'teardown',
},
{
name: 'teardown',
testMatch: /global.teardown\.ts/,
},
{
name: 'chromium',
use: devices['Desktop Chrome'],
dependencies: ['setup'],
},
{
name: 'firefox',
use: devices['Desktop Firefox'],
dependencies: ['setup'],
},
{
name: 'webkit',
use: devices['Desktop Safari'],
dependencies: ['setup'],
},
],
}); -
新方法
expect.configure用于创建具有自身默认值(如timeout和soft)的预配置 expect 实例。const slowExpect = expect.configure({ timeout: 10000 });
await slowExpect(locator).toHaveText('Submit');
// Always do soft assertions.
const softExpect = expect.configure({ soft: true }); -
testConfig.webServer 中的新选项
stderr和stdout用于配置输出处理:playwright.config.tsimport { defineConfig } from '@playwright/test';
export default defineConfig({
// Run your local dev server before starting the tests
webServer: {
command: 'npm run start',
url: 'http://127.0.0.1:3000',
reuseExistingServer: !process.env.CI,
stdout: 'pipe',
stderr: 'pipe',
},
}); -
新的 locator.and() 用于创建一个同时匹配两个定位器的定位器。
const button = page.getByRole('button').and(page.getByTitle('Subscribe')); -
新的事件 browserContext.on('console') 和 browserContext.on('dialog') 可用于订阅来自指定浏览器上下文中任意页面的对话框和控制台消息。使用新的方法 consoleMessage.page() 和 dialog.page() 来精确定位事件来源。
⚠️ 重大更改
🌐 ⚠️ Breaking changes
-
npx playwright test如果同时安装playwright和@playwright/test就无法使用。其实没必要同时安装两个,因为你可以直接从@playwright/test导入浏览器自动化 API:automation.tsimport { chromium, firefox, webkit } from '@playwright/test';
/* ... */ -
Node.js 14 自 2023 年 4 月 30 日 达到生命周期结束 后不再受支持。
浏览器版本
🌐 Browser Versions
- Chromium 114.0.5735.26
- 火狐浏览器 113.0
- 网络工具包 16.4
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- 谷歌浏览器 113
- 微软 Edge 113
1.33 版本
🌐 Version 1.33
定位器更新
🌐 Locators Update
-
使用 locator.or() 创建一个匹配两个定位器中任意一个的定位器。考虑这样一个场景:你想点击“新建邮件”按钮,但有时会弹出安全设置对话框。在这种情况下,你可以等待“新建邮件”按钮或对话框出现,并据此采取相应操作:
const newEmail = page.getByRole('button', { name: 'New email' });
const dialog = page.getByText('Confirm security settings');
await expect(newEmail.or(dialog)).toBeVisible();
if (await dialog.isVisible())
await page.getByRole('button', { name: 'Dismiss' }).click();
await newEmail.click(); -
在 locator.filter() 中使用新选项 hasNot 和 hasNotText 来查找 不符合 某些条件的元素。
const rowLocator = page.locator('tr');
await rowLocator
.filter({ hasNotText: 'text in column 1' })
.filter({ hasNot: page.getByRole('button', { name: 'column 2 button' }) })
.screenshot(); -
使用新的以网页为优先的断言 expect(locator).toBeAttached() 来确保元素存在于页面的 DOM 中。不要与 expect(locator).toBeVisible() 混淆,后者确保元素既已附加又可见。
新 API
🌐 New APIs
- locator.or()
- 在 locator.filter() 中新增选项 hasNot
- 新选项 hasNotText 在 locator.filter() 中
- expect(locator).toBeAttached()
- 在 route.fetch() 中新增选项 timeout
- reporter.onExit()
⚠️ 重大变更
🌐 ⚠️ Breaking change
mcr.microsoft.com/playwright:v1.33.0现在提供基于 Ubuntu Jammy 的 Playwright 镜像。如需使用基于 Focal 的镜像,请改用mcr.microsoft.com/playwright:v1.33.0-focal。
浏览器版本
🌐 Browser Versions
- Chromium 113.0.5672.53
- 火狐浏览器 112.0
- 网络工具包 16.4
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- 谷歌浏览器 112
- 微软 Edge 112
1.32 版本
🌐 Version 1.32
UI 模式简介(预览)
🌐 Introducing UI Mode (preview)
新的UI模式让你可以探索、运行和调试测试。内置了监视模式。
🌐 New UI Mode lets you explore, run and debug tests. Comes with a built-in watch mode.

使用新的标志 --ui:
🌐 Engage with a new flag --ui:
npx playwright test --ui
新 API
🌐 New APIs
- page.routeFromHAR() 和 browserContext.routeFromHAR() 中的新选项 updateMode 和 updateContent。
- 链接现有的定位器对象,详情请参见 定位器文档 。
- 新属性 testInfo.testId。
- 方法 tracing.startChunk() 中的新选项 name。
⚠️ 组件测试中的重大变更
🌐 ⚠️ Breaking change in component tests
注意:仅组件测试,不影响端到端测试。
🌐 Note: component tests only, does not affect end-to-end tests.
@playwright/experimental-ct-react现在仅支持 React 18。- 如果你在使用 React 16 或 17 运行组件测试,请将
@playwright/experimental-ct-react替换为@playwright/experimental-ct-react17。
浏览器版本
🌐 Browser Versions
- Chromium 112.0.5615.29
- 火狐浏览器 111.0
- 网络工具包 16.4
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- 谷歌浏览器 111
- 微软 Edge 111
1.31 版本
🌐 Version 1.31
新 API
🌐 New APIs
-
新增了 [testProject.dependencies](/api/class-testproject.mdx#test-project-dependencies) 属性,用于配置项目间的依赖。
使用依赖允许全局设置生成跟踪和其他工件,请参阅测试报告中的设置步骤等。
playwright.config.tsimport { defineConfig } from '@playwright/test';
export default defineConfig({
projects: [
{
name: 'setup',
testMatch: /global.setup\.ts/,
},
{
name: 'chromium',
use: devices['Desktop Chrome'],
dependencies: ['setup'],
},
{
name: 'firefox',
use: devices['Desktop Firefox'],
dependencies: ['setup'],
},
{
name: 'webkit',
use: devices['Desktop Safari'],
dependencies: ['setup'],
},
],
}); -
新的断言 expect(locator).toBeInViewport() 确保 locator 指向的元素与视口相交,根据 交叉观察者 API。
const button = page.getByRole('button');
// Make sure at least some part of element intersects viewport.
await expect(button).toBeInViewport();
// Make sure element is fully outside of viewport.
await expect(button).not.toBeInViewport();
// Make sure that at least half of the element intersects viewport.
await expect(button).toBeInViewport({ ratio: 0.5 });
杂项
🌐 Miscellaneous
- 现在可以在单独的窗口中打开跟踪查看器中的 DOM 快照。
- 在
playwright.config中使用的新方法defineConfig。 - 方法 route.fetch() 的新选项 maxRedirects。
- Playwright 现在支持 Debian 11 arm64。
- 官方 docker 镜像 现在包含的是 Node 18,而不是 Node 16。
⚠️ 组件测试中的重大变更
🌐 ⚠️ Breaking change in component tests
注意:仅组件测试,不影响端到端测试。
🌐 Note: component tests only, does not affect end-to-end tests.
playwright-ct.config 配置文件用于 组件测试 现在需要调用 defineConfig。
// Before
import { type PlaywrightTestConfig, devices } from '@playwright/experimental-ct-react';
const config: PlaywrightTestConfig = {
// ... config goes here ...
};
export default config;
将 config 变量定义替换为 defineConfig 调用:
🌐 Replace config variable definition with defineConfig call:
// After
import { defineConfig, devices } from '@playwright/experimental-ct-react';
export default defineConfig({
// ... config goes here ...
});
浏览器版本
🌐 Browser Versions
- Chromium 111.0.5563.19
- 火狐浏览器 109.0
- 网络工具包 16.4
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- 谷歌浏览器 110
- 微软 Edge 110
1.30 版本
🌐 Version 1.30
浏览器版本
🌐 Browser Versions
- Chromium 110.0.5481.38
- 火狐浏览器 108.0.2
- 网络工具包 16.4
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- 谷歌浏览器 109
- 微软 Edge 109
1.29 版本
🌐 Version 1.29
新 API
🌐 New APIs
-
新方法 route.fetch() 和 route.fulfill() 的新选项
json:await page.route('**/api/settings', async route => {
// Fetch original settings.
const response = await route.fetch();
// Force settings theme to a predefined value.
const json = await response.json();
json.theme = 'Solorized';
// Fulfill with modified data.
await route.fulfill({ json });
}); -
新方法 locator.all() 用于遍历所有匹配的元素:
// Check all checkboxes!
const checkboxes = page.getByRole('checkbox');
for (const checkbox of await checkboxes.all())
await checkbox.check(); -
locator.selectOption() 现在可以按值或标签匹配:
<select multiple>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>await element.selectOption('Red'); -
重试代码块,直到所有断言都通过:
await expect(async () => {
const response = await page.request.get('https://api.example.com');
await expect(response).toBeOK();
}).toPass();在我们的文档中阅读更多内容。
-
在测试失败时自动捕获完整页面截图:
playwright.config.tsimport { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
screenshot: {
mode: 'only-on-failure',
fullPage: true,
}
}
});
杂项
🌐 Miscellaneous
- Playwright 测试现在会遵守
jsconfig.json。 - 为 androidDevice.launchBrowser() 提供了新的选项
args和proxy。 - 方法 route.continue() 中的选项
postData现在支持 Serializable 值。
浏览器版本
🌐 Browser Versions
- Chromium 109.0.5414.46
- 火狐浏览器 107.0
- 网络工具包 16.4
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- 谷歌浏览器 108
- 微软 Edge 108
1.28 版本
🌐 Version 1.28
Playwright 工具
🌐 Playwright Tools
- 在 VSCode 中记录光标位置。 你可以运行测试,将光标定位到测试末尾,然后继续生成测试。

- VSCode 中的实时定位器。 你可以在 VSCode 中悬停并编辑定位器,以在打开的浏览器中高亮显示它们。
- CodeGen 中的实时定位器。 使用“探索”工具为页面上的任何元素生成定位器。

- 代码生成器和追踪查看器深色主题。 将自动根据操作系统设置选择。

测试运行器
🌐 Test Runner
-
使用 test.describe.configure() 为文件或测试配置重试次数和测试超时。
// Each test in the file will be retried twice and have a timeout of 20 seconds.
test.describe.configure({ retries: 2, timeout: 20_000 });
test('runs first', async ({ page }) => {});
test('runs second', async ({ page }) => {}); -
使用 testProject.snapshotPathTemplate 和 testConfig.snapshotPathTemplate 配置一个模板,用于控制由 expect(page).toHaveScreenshot() 和 expect(value).toMatchSnapshot() 生成的快照的位置。
playwright.config.tsimport { defineConfig } from '@playwright/test';
export default defineConfig({
testDir: './tests',
snapshotPathTemplate: '{testDir}/__screenshots__/{testFilePath}/{arg}{ext}',
});
新 API
🌐 New APIs
- locator.blur()
- locator.clear()
- android.launchServer() and android.connect()
- androidDevice.on('close')
浏览器版本
🌐 Browser Versions
- Chromium 108.0.5359.29
- 火狐浏览器 106.0
- 网络工具包 16.4
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- 谷歌浏览器 107
- 微软 Edge 107
1.27 版本
🌐 Version 1.27
定位器
🌐 Locators
使用这些新的 API 编写定位器是一种乐趣:
🌐 With these new APIs writing locators is a joy:
- page.getByText() 用于通过文本内容定位。
- page.getByRole() to locate by ARIA role, ARIA attributes and accessible name.
- page.getByLabel() 根据关联标签的文本定位表单控件。
- page.getByTestId() to locate an element based on its
data-testidattribute (other attribute can be configured). - page.getByPlaceholder() 通过占位符定位输入框。
- page.getByAltText() 用于通过元素的替代文本(通常是图片)来定位元素。
- page.getByTitle() 通过标题定位元素。
await page.getByLabel('User Name').fill('John');
await page.getByLabel('Password').fill('secret-password');
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page.getByText('Welcome, John!')).toBeVisible();
所有相同的方法也可以在 Locator、FrameLocator 和 Frame 类中使用。
🌐 All the same methods are also available on Locator, FrameLocator and Frame classes.
其他亮点
🌐 Other highlights
-
playwright.config.ts中的workers选项现在可以接受百分比字符串,以使用部分可用的 CPU。你也可以在命令行中传递它:npx playwright test --workers=20% -
为 HTML 报告器新增选项
host和port。import { defineConfig } from '@playwright/test';
export default defineConfig({
reporter: [['html', { host: 'localhost', port: '9223' }]],
}); -
新的字段
FullConfig.configFile可供测试报告使用,用于指定配置文件的路径(如果有的话)。 -
正如在 v1.25 中宣布的,Ubuntu 18 自 2022 年 12 月起将不再受支持。此外,从下一个 Playwright 版本开始,Ubuntu 18 将不再有 WebKit 更新。
行为改变
🌐 Behavior Changes
-
expect(locator).toHaveAttribute() 的空值不再匹配缺失的属性。例如,以下代码片段在
button没有disabled属性时将会成功。await expect(page.getByRole('button')).toHaveAttribute('disabled', ''); -
命令行选项
--grep和--grep-invert之前会错误地忽略配置中指定的grep和grepInvert选项。现在它们都会一起应用。
浏览器版本
🌐 Browser Versions
- Chromium 107.0.5304.18
- 火狐浏览器 105.0.1
- 网络工具包 16.0
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- 谷歌浏览器 106
- 微软 Edge 106
1.26 版本
🌐 Version 1.26
断言
🌐 Assertions
- 为 expect(locator).toBeEnabled() 提供了新选项
enabled。 - expect(locator).toHaveText() 现在可以穿透打开的 shadow roots。
- 为 expect(locator).toBeEditable() 提供了新选项
editable。 - 为 expect(locator).toBeVisible() 提供了新选项
visible。
其他亮点
🌐 Other highlights
- 为 apiRequestContext.get() 及其他方法新增选项
maxRedirects,用于限制重定向次数。 - 新的命令行标志
--pass-with-no-tests,允许在未找到文件时测试套件仍然通过。 - 新的命令行标志
--ignore-snapshots用于跳过快照预期,例如expect(value).toMatchSnapshot()和expect(page).toHaveScreenshot()。
行为改变
🌐 Behavior Change
一堆 Playwright API 已经支持 waitUntil: 'domcontentloaded' 选项。例如:
🌐 A bunch of Playwright APIs already support the waitUntil: 'domcontentloaded' option. For example:
await page.goto('https://playwright.nodejs.cn', {
waitUntil: 'domcontentloaded',
});
在 1.26 之前,这将等待所有 iframe 触发 DOMContentLoaded 事件。
🌐 Prior to 1.26, this would wait for all iframes to fire the DOMContentLoaded event.
为了符合网页规范,'domcontentloaded' 值仅等待目标框架触发 'DOMContentLoaded' 事件。使用 waitUntil: 'load' 来等待所有子框架。
🌐 To align with web specification, the 'domcontentloaded' value only waits for the target frame to fire the 'DOMContentLoaded' event. Use waitUntil: 'load' to wait for all iframes.
浏览器版本
🌐 Browser Versions
- Chromium 106.0.5249.30
- 火狐浏览器 104.0
- 网络工具包 16.0
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- 谷歌浏览器 105
- 微软 Edge 105
1.25 版本
🌐 Version 1.25
VSCode 扩展
🌐 VSCode Extension
- 监视实时运行的测试并保持开发工具打开。
- 选择选择器。
- 从当前页面状态记录新测试。

测试运行器
🌐 Test Runner
-
test.step() 现在返回 step 函数的值:
test('should work', async ({ page }) => {
const pageTitle = await test.step('get title', async () => {
await page.goto('https://playwright.nodejs.cn');
return await page.title();
});
console.log(pageTitle);
}); -
新的
'interrupted'测试状态。 -
通过 CLI 标志启用跟踪:
npx playwright test --trace=on。
公告
🌐 Announcements
- 🎁 我们现在提供 Ubuntu 22.04 Jammy Jellyfish 的 Docker 镜像:
mcr.microsoft.com/playwright:v1.34.0-jammy。 - 🪦 这是最后一个支持 macOS 10.15 的版本(从1.21版本起不再支持)。
- 🪦 这是最后一个支持 Node.js 12 的版本,建议升级到 Node.js LTS(16)。
- ⚠️ Ubuntu 18 已不再支持,自 2022 年 12 月起停止维护。
浏览器版本
🌐 Browser Versions
- Chromium 105.0.5195.19
- 火狐浏览器 103.0
- 网络工具包 16.0
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- 谷歌浏览器 104
- 微软 Edge 104
1.24 版本
🌐 Version 1.24
🌍 playwright.config.ts 中的多个网络服务器
🌐 🌍 Multiple Web Servers in playwright.config.ts
通过传递一组配置来启动多个 Web 服务器、数据库或其他进程:
🌐 Launch multiple web servers, databases, or other processes by passing an array of configurations:
import { defineConfig } from '@playwright/test';
export default defineConfig({
webServer: [
{
command: 'npm run start',
url: 'http://127.0.0.1:3000',
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
},
{
command: 'npm run backend',
url: 'http://127.0.0.1:3333',
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
}
],
use: {
baseURL: 'http://localhost:3000/',
},
});
🐂 Debian 11 Bullseye 支持
🌐 🐂 Debian 11 Bullseye Support
Playwright 现在支持在 x86_64 上的 Debian 11 Bullseye 使用 Chromium、Firefox 和 WebKit。如果你遇到任何问题,请告诉我们!
🌐 Playwright now supports Debian 11 Bullseye on x86_64 for Chromium, Firefox and WebKit. Let us know if you encounter any issues!
Linux 支持如下所示:
🌐 Linux support looks like this:
| Ubuntu 20.04 | Ubuntu 22.04 | Debian 11 | |
|---|---|---|---|
| Chromium | ✅ | ✅ | ✅ |
| WebKit | ✅ | ✅ | ✅ |
| Firefox | ✅ | ✅ | ✅ |
🕵️ 匿名描述
🌐 🕵️ Anonymous Describe
现在可以调用 test.describe() 来创建没有标题的测试套件。这对于使用 test.use() 为一组测试设置共同的选项非常有用。
🌐 It is now possible to call test.describe() to create suites without a title. This is useful for giving a group of tests a common option with test.use().
test.describe(() => {
test.use({ colorScheme: 'dark' });
test('one', async ({ page }) => {
// ...
});
test('two', async ({ page }) => {
// ...
});
});
🧩 组件测试更新
🌐 🧩 Component Tests Update
Playwright 1.24 组件测试引入了 beforeMount 和 afterMount 钩子。使用它们来为测试配置你的应用。
🌐 Playwright 1.24 Component Tests introduce beforeMount and afterMount hooks. Use these to configure your app for tests.
例如,这可以用于在 Vue.js 中设置应用路由:
🌐 For example, this could be used to setup App router in Vue.js:
import { test } from '@playwright/experimental-ct-vue';
import { Component } from './mycomponent';
test('should work', async ({ mount }) => {
const component = await mount(Component, {
hooksConfig: {
/* anything to configure your app */
}
});
});
import { router } from '../router';
import { beforeMount } from '@playwright/experimental-ct-vue/hooks';
beforeMount(async ({ app, hooksConfig }) => {
app.use(router);
});
Next.js 中的类似配置如下所示:
🌐 A similar configuration in Next.js would look like this:
import { test } from '@playwright/experimental-ct-react';
import { Component } from './mycomponent';
test('should work', async ({ mount }) => {
const component = await mount(<Component></Component>, {
// Pass mock value from test into `beforeMount`.
hooksConfig: {
router: {
query: { page: 1, per_page: 10 },
asPath: '/posts'
}
}
});
});
import router from 'next/router';
import { beforeMount } from '@playwright/experimental-ct-react/hooks';
beforeMount(async ({ hooksConfig }) => {
// Before mount, redefine useRouter to return mock value from test.
router.useRouter = () => hooksConfig.router;
});
1.23 版本
🌐 Version 1.23
网络重播
🌐 Network Replay
现在,你可以将网络流量记录到 HAR 文件中,并在测试中重复使用此流量。
🌐 Now you can record network traffic into a HAR file and re-use this traffic in your tests.
将网络记录到 HAR 文件中:
🌐 To record network into HAR file:
npx playwright open --save-har=github.har.zip https://github.com/microsoft
或者,你可以通过编程方式记录 HAR:
🌐 Alternatively, you can record HAR programmatically:
const context = await browser.newContext({
recordHar: { path: 'github.har.zip' }
});
// ... do stuff ...
await context.close();
使用新的方法 page.routeFromHAR() 或 browserContext.routeFromHAR() 从 HAR 文件中提供匹配的响应:
🌐 Use the new methods page.routeFromHAR() or browserContext.routeFromHAR() to serve matching responses from the HAR file:
await context.routeFromHAR('github.har.zip');
在我们的文档中阅读更多内容。
🌐 Read more in our documentation.
高级路由
🌐 Advanced Routing
你现在可以使用 route.fallback() 将路由延迟到其他处理程序。
🌐 You can now use route.fallback() to defer routing to other handlers.
考虑以下示例:
🌐 Consider the following example:
// Remove a header from all requests.
test.beforeEach(async ({ page }) => {
await page.route('**/*', async route => {
const headers = await route.request().allHeaders();
delete headers['if-none-match'];
await route.fallback({ headers });
});
});
test('should work', async ({ page }) => {
await page.route('**/*', async route => {
if (route.request().resourceType() === 'image')
await route.abort();
else
await route.fallback();
});
});
请注意,新的方法 page.routeFromHAR() 和 browserContext.routeFromHAR() 同样参与路由,并且可以被延迟调用。
🌐 Note that the new methods page.routeFromHAR() and browserContext.routeFromHAR() also participate in routing and could be deferred to.
Web 优先断言更新
🌐 Web-First Assertions Update
- 新方法 expect(locator).toHaveValues(),用于断言
<select multiple>元素的所有选定值。 - 方法 expect(locator).toContainText() 和 expect(locator).toHaveText() 现在接受
ignoreCase选项。
组件测试更新
🌐 Component Tests Update
- 通过
@playwright/experimental-ct-vue2包支持 Vue2。 - 支持在
.js文件中的组件进行 create-react-app 的组件测试。
阅读更多关于 使用 Playwright 进行组件测试 的内容。
🌐 Read more about component testing with Playwright.
杂项
🌐 Miscellaneous
-
如果有一个阻碍你的服务工作者,你现在可以通过新的上下文选项
serviceWorkers轻松禁用它:playwright.config.tsexport default {
use: {
serviceWorkers: 'block',
}
}; -
使用
.zip路径作为recordHar上下文选项会自动压缩生成的 HAR:const context = await browser.newContext({
recordHar: {
path: 'github.har.zip',
}
}); -
如果你打算手动编辑 HAR,可以考虑使用只记录重放所需信息的
"minimal"HAR 记录模式:const context = await browser.newContext({
recordHar: {
path: 'github.har',
mode: 'minimal',
}
}); -
Playwright 现在可以在 Ubuntu 22 amd64 和 Ubuntu 22 arm64 上运行。我们还发布了新的 Docker 镜像
mcr.microsoft.com/playwright:v1.34.0-jammy。
⚠️ 重大更改 ⚠️
🌐 ⚠️ Breaking Changes ⚠️
如果对指定 URL 的请求返回以下任意 HTTP 状态码,WebServer 现在将被视为“就绪”:
🌐 WebServer is now considered "ready" if request to the specified url has any of the following HTTP status codes:
200-299300-399(新)400、401、402、403(新)
1.22 版本
🌐 Version 1.22
高亮
🌐 Highlights
-
组件测试(预览)
Playwright Test 现在可以测试你的 React、Vue.js 或 Svelte 组件。你可以在真实浏览器中运行组件的同时,使用 Playwright Test 的所有功能(例如并行化、模拟和调试)。
典型的组件测试如下所示:
App.spec.tsximport { test, expect } from '@playwright/experimental-ct-react';
import App from './App';
// Let's test component in a dark scheme!
test.use({ colorScheme: 'dark' });
test('should render', async ({ mount }) => {
const component = await mount(<App></App>);
// As with any Playwright test, assert locator text.
await expect(component).toContainText('React');
// Or do a screenshot 🚀
await expect(component).toHaveScreenshot();
// Or use any Playwright method
await component.click();
});在我们的文档中阅读更多内容。
-
角色选择器,允许通过其 ARIA 角色、ARIA 属性 和 可访问名称 来选择元素。
// Click a button with accessible name "log in"
await page.locator('role=button[name="log in"]').click();在我们的文档中阅读更多内容。
-
新的 locator.filter() API 用于过滤现有的定位器
const buttons = page.locator('role=button');
// ...
const submitButton = buttons.filter({ hasText: 'Submit' });
await submitButton.click(); -
新的网页优先断言 [expect(page).toHaveScreenshot()](/api/class-pageassertions.mdx#page-assertions-to-have-screenshot-1)和 [expect(locator).toHaveScreenshot()](/api/class-locatorassertions.mdx#locator-assertions-to-have-screenshot-1),等待截图稳定并提升测试可靠性。
新断言具有特定于屏幕截图的默认值,例如:
- 禁用动画
- 使用 CSS 缩放选项
await page.goto('https://playwright.nodejs.cn');
await expect(page).toHaveScreenshot();新的 [expect(page).toHaveScreenshot()](/api/class-pageassertions.mdx#page-assertions-to-have-screenshot-1) 将截图保存在与 [expect(value).toMatchSnapshot()](/api/class-snapshotassertions.mdx#snapshot-assertions-to-match-snapshot-1)相同的位置。
1.21 版本
🌐 Version 1.21
高亮
🌐 Highlights
-
新的角色选择器允许通过它们的 ARIA 角色、ARIA 属性 和 可访问名称 来选择元素。
// Click a button with accessible name "log in"
await page.locator('role=button[name="log in"]').click();在我们的文档中阅读更多内容。
-
在 page.screenshot() 中新增
scale选项,可用于截取较小尺寸的截图。 -
[page.screenshot()](/api/class-page.mdx#page-screenshot)中新增
caret选项,用于控制文本光标。默认值为"hide"。 -
等待任意条件的新方法
expect.poll:// Poll the method until it returns an expected result.
await expect.poll(async () => {
const response = await page.request.get('https://api.example.com');
return response.status();
}).toBe(200);expect.poll支持大多数同步匹配器,比如.toBe()、.toContain()等。更多信息请查看 我们的文档。
行为改变
🌐 Behavior Changes
- 运行 TypeScript 测试时的 ESM 支持现在默认已启用。不再需要
PLAYWRIGHT_EXPERIMENTAL_TS_ESM环境变量。 mcr.microsoft.com/playwrightDocker 镜像不再包含 Python。请使用mcr.microsoft.com/playwright/python作为带有预装 Python 的 Playwright 准备好 Docker 镜像。- Playwright 现在通过 locator.setInputFiles() API 支持大文件上传(数百 MB)。
浏览器版本
🌐 Browser Versions
- Chromium 101.0.4951.26
- 火狐浏览器 98.0.2
- 网络工具包 15.4
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- 谷歌浏览器 100
- 微软 Edge 100
1.20 版本
🌐 Version 1.20
高亮
🌐 Highlights
-
方法 page.screenshot()、locator.screenshot() 和 elementHandle.screenshot() 的新选项:
- 选项
animations: "disabled"会将所有 CSS 动画和过渡回滚到一致的状态 - 选项
mask: Locator[]会遮盖指定的元素,用粉红色#FF00FF方框覆盖它们。
- 选项
-
expect().toMatchSnapshot()现在支持匿名快照:当快照名称缺失时,Playwright Test 会自动生成一个:expect('Web is Awesome <3').toMatchSnapshot(); -
使用
expect().toMatchSnapshot()进行细粒度截图比较的新maxDiffPixels和maxDiffPixelRatio选项:expect(await page.screenshot()).toMatchSnapshot({
maxDiffPixels: 27, // allow no more than 27 different pixels.
});在testConfig.expect中指定
maxDiffPixels或maxDiffPixelRatio一次是最方便的。 -
Playwright Test 现在增加了 testConfig.fullyParallel 模式。默认情况下,Playwright Test 会在文件之间进行并行。在完全并行模式下,单个文件内的测试也会并行运行。你也可以使用
--fully-parallel命令行标志。playwright.config.tsexport default {
fullyParallel: true,
}; -
testProject.grep 和 testProject.grepInvert 现在可以针对每个项目进行配置。例如,现在你可以使用
grep来配置冒烟测试项目:playwright.config.tsexport default {
projects: [
{
name: 'smoke tests',
grep: /@smoke/,
},
],
}; -
Trace Viewer 现在显示 API 测试请求。
-
locator.highlight() 可直观显示元素,以便更容易进行调试。
公告
🌐 Announcements
- 我们现在提供指定的 Python Docker 镜像
mcr.microsoft.com/playwright/python。如果你使用 Python,请改用该镜像。这是最后一个包含 Python 的我们的 JavaScriptmcr.microsoft.com/playwrightDocker 镜像的版本。 - v1.20 是最后一个为 macOS 10.15 Catalina 提供 WebKit 更新的版本。请更新 macOS 以继续使用最新最强大的 WebKit!
浏览器版本
🌐 Browser Versions
- Chromium 101.0.4921.0
- 火狐浏览器 97.0.1
- 网络工具包 15.4
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- 谷歌浏览器 99
- 微软 Edge 99
1.19 版本
🌐 Version 1.19
Playwright 测试更新
🌐 Playwright Test Update
-
Playwright Test v1.19 现在支持软断言。失败的软断言
不要 终止测试执行,但将测试标记为失败。
// Make a few checks that will not stop the test when failed...
await expect.soft(page.locator('#status')).toHaveText('Success');
await expect.soft(page.locator('#eta')).toHaveText('1 day');
// ... and continue the test to check more things.
await page.locator('#next-page').click();
await expect.soft(page.locator('#title')).toHaveText('Make another order');在我们的文档中阅读更多内容
-
现在,你可以将 自定义期望消息 作为第二个参数传递给
expect和expect.soft函数,例如:await expect(page.locator('text=Name'), 'should be logged in').toBeVisible();错误看起来像这样:
Error: should be logged in
Call log:
- expect.toBeVisible with timeout 5000ms
- waiting for "getByText('Name')"
2 |
3 | test('example test', async({ page }) => {
> 4 | await expect(page.locator('text=Name'), 'should be logged in').toBeVisible();
| ^
5 | });
6 |在我们的文档中阅读更多内容
-
默认情况下,测试会按顺序在单个文件中运行。如果你在一个文件中有许多独立测试,现在可以与 [test.describe.configure()](/api/class-test.mdx#test-describe-configure) 并行运行。
其他更新
🌐 Other Updates
-
Locator 现在支持一个
has选项,可以确保它内部包含另一个定位器:await page.locator('article', {
has: page.locator('.highlight'),
}).click();在定位器文档中阅读更多内容
-
page.screenshot() 和 locator.screenshot() 现在会自动隐藏闪烁的光标
-
Playwright Codegen 现在生成定位器和帧定位器
-
testConfig.webServer 中的新选项
url用于确保在运行测试之前你的 Web 服务器已准备就绪 -
新的 testInfo.errors 和 testResult.errors 包含所有失败的断言和软断言。
Playwright 测试全局设置可能发生重大变化
🌐 Potentially breaking change in Playwright Test Global Setup
此更改不太可能影响你,如果你的测试继续按原样运行,则无需采取任何操作。
🌐 It is unlikely that this change will affect you, no action is required if your tests keep running as they did.
我们注意到,在极少数情况下,要执行的测试集合是通过环境变量在全局设置中配置的。我们还注意到一些应用在全局清理中对报告器的输出进行了后处理。如果你正在做上述两种情况之一,了解更多
🌐 We've noticed that in rare cases, the set of tests to be executed was configured in the global setup by means of the environment variables. We also noticed some applications that were post processing the reporters' output in the global teardown. If you are doing one of the two, learn more
浏览器版本
🌐 Browser Versions
- Chromium 100.0.4863.0
- 火狐浏览器 96.0.1
- 网络工具包 15.4
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- 谷歌浏览器 98
- 微软 Edge 98
1.18 版本
🌐 Version 1.18
定位器改进
🌐 Locator Improvements
-
现在可以选择通过每个定位器包含的文本来过滤每个定位器:
await page.locator('li', { hasText: 'my item' }).locator('button').click();在定位器文档中阅读更多内容
测试 API 改进
🌐 Testing API improvements
改进的 TypeScript 支持
🌐 Improved TypeScript Support
- Playwright Test 现在支持
tsconfig.json的baseUrl和paths,因此你可以使用别名 - 有一个新的环境变量
PW_EXPERIMENTAL_TS_ESM,允许在你的 TypeScript 代码中导入 ESM 模块,而无需编译步骤。导入 ESM 模块时别忘了加上.js后缀。按如下方式运行你的测试:
npm i --save-dev @playwright/test@1.18.0-rc1
PW_EXPERIMENTAL_TS_ESM=1 npx playwright test
创建 Playwright
🌐 Create Playwright
“npm init playwright”命令现已公开供你使用:
🌐 The npm init playwright command is now generally available for your use:
# Run from your project's root directory
npm init playwright@latest
# Or create a new project
npm init playwright@latest new-project
这将创建一个 Playwright 测试配置文件,可选地添加示例、GitHub Action 工作流以及第一个测试 example.spec.ts。
🌐 This will create a Playwright Test configuration file, optionally add examples, a GitHub Action workflow and a first test example.spec.ts.
新的 API 和更改
🌐 New APIs & changes
- 新的
testCase.repeatEachIndexAPI acceptDownloads选项现在默认为true
重大更改:自定义配置选项
🌐 Breaking change: custom config options
自定义配置选项是一种使用不同值为项目设置参数的便捷方式。更多信息请参阅本指南。
🌐 Custom config options are a convenient way to parametrize projects with different values. Learn more in this guide.
以前,通过 test.extend() 引入的任何夹具都可以在 testProject.use 配置部分中被覆盖。例如,
🌐 Previously, any fixture introduced through test.extend() could be overridden in the testProject.use config section. For example,
// WRONG: THIS SNIPPET DOES NOT WORK SINCE v1.18.
// fixtures.js
const test = base.extend({
myParameter: 'default',
});
// playwright.config.js
module.exports = {
use: {
myParameter: 'value',
},
};
在配置文件中将夹具参数化的正确方法是在定义夹具时指定 option: true。例如,
🌐 The proper way to make a fixture parametrized in the config file is to specify option: true when defining the fixture. For example,
// CORRECT: THIS SNIPPET WORKS SINCE v1.18.
// fixtures.js
const test = base.extend({
// Fixtures marked as "option: true" will get a value specified in the config,
// or fallback to the default value.
myParameter: ['default', { option: true }],
});
// playwright.config.js
module.exports = {
use: {
myParameter: 'value',
},
};
浏览器版本
🌐 Browser Versions
- Chromium 99.0.4812.0
- 火狐浏览器 95.0
- 网络工具包 15.4
该版本还针对以下稳定渠道进行了测试:
🌐 This version was also tested against the following stable channels:
- 谷歌浏览器 97
- 微软 Edge 97
1.17 版本
🌐 Version 1.17
框架定位器
🌐 Frame Locators
Playwright 1.17 引入了 frame locators——页面中 iframe 的定位器。框架定位器包含足够的逻辑来获取 iframe,然后在该 iframe 中定位元素。框架定位器默认是严格的,会等待 iframe 出现,并且可以用于 Web-First 断言。
🌐 Playwright 1.17 introduces frame locators - a locator to the iframe on the page. Frame locators capture the logic sufficient to retrieve the iframe and then locate elements in that iframe. Frame locators are strict by default, will wait for iframe to appear and can be used in Web-First assertions.

框架定位器可以通过 page.frameLocator() 或 locator.frameLocator() 方法创建。
🌐 Frame locators can be created with either page.frameLocator() or locator.frameLocator() method.
const locator = page.frameLocator('#my-iframe').locator('text=Submit');
await locator.click();
查看更多内容请访问 我们的文档。
🌐 Read more at our documentation.
跟踪查看器更新
🌐 Trace Viewer Update
Playwright Trace Viewer 现在可以在 https://trace.playwright.dev 在线使用!只需将你的 trace.zip 文件拖放到页面上即可查看其内容。
🌐 Playwright Trace Viewer is now available online at https://trace.playwright.dev! Just drag-and-drop your trace.zip file to inspect its contents.
注意:跟踪文件不会被上传到任何地方;trace.playwright.dev 是一个渐进式网络应用,在本地处理跟踪。
- Playwright 测试跟踪现在默认包括源(可以使用跟踪选项关闭这些源)
- 跟踪查看器现在显示测试名称
- 包含浏览器详细信息的新跟踪元数据选项卡
- 快照现在有 URL 栏

HTML 报告更新
🌐 HTML Report Update
- HTML 报告现在支持动态过滤
- 报告现在是一个单一的静态 HTML 文件,可以通过电子邮件发送或作为 Slack 附件发送。

Ubuntu ARM64 支持及更多
🌐 Ubuntu ARM64 support + more
-
Playwright 现在支持 Ubuntu 20.04 ARM64。你现在可以在 Apple M1 和树莓派上通过 Docker 运行 Playwright 测试。
-
你现在可以使用 Playwright 在 Linux 上安装稳定版本的 Edge:
npx playwright install msedge
新 API
🌐 New APIs
- 追踪现在支持
'title'选项 - 页面导航支持新的
'commit'等待选项 - HTML 报告器获得了new 配置选项
testConfig.snapshotDir选项testInfo.parallelIndextestInfo.titlePathtestOptions.trace有新选项expect.toMatchSnapshot支持子目录reporter.printsToStdio()
1.16 版本
🌐 Version 1.16
🎭 Playwright测试
🌐 🎭 Playwright Test
API 测试
🌐 API Testing
Playwright 1.16 引入了新的 API 测试,让你可以直接从 Node.js 向服务器发送请求!现在你可以:
🌐 Playwright 1.16 introduces new API Testing that lets you send requests to the server directly from Node.js! Now you can:
- 测试你的服务器 API
- 在测试中访问 Web 应用之前准备服务器端状态
- 在浏览器中运行某些操作后验证服务器端后置条件
要代表 Playwright 的页面发起请求,请使用 新的 page.request API :
🌐 To do a request on behalf of Playwright's Page, use new page.request API:
import { test, expect } from '@playwright/test';
test('context fetch', async ({ page }) => {
// Do a GET request on behalf of page
const response = await page.request.get('http://example.com/foo.json');
// ...
});
要从 node.js 向 API 端点发起独立请求,请使用 新的 request 工具:
🌐 To do a stand-alone request from node.js to an API endpoint, use new request fixture:
import { test, expect } from '@playwright/test';
test('context fetch', async ({ request }) => {
// Do a GET request on behalf of page
const response = await request.get('http://example.com/foo.json');
// ...
});
在我们的API 测试指南中阅读更多内容。
🌐 Read more about it in our API testing guide.
响应拦截
🌐 Response Interception
现在可以通过结合 API 测试 和 请求拦截 来进行响应拦截。
🌐 It is now possible to do response interception by combining API Testing with request interception.
例如,我们可以对页面上的所有图片进行模糊处理:
🌐 For example, we can blur all the images on the page:
import { test, expect } from '@playwright/test';
import jimp from 'jimp'; // image processing library
test('response interception', async ({ page }) => {
await page.route('**/*.jpeg', async route => {
const response = await page._request.fetch(route.request());
const image = await jimp.read(await response.body());
await image.blur(5);
await route.fulfill({
response,
body: await image.getBufferAsync('image/jpeg'),
});
});
const response = await page.goto('https://playwright.nodejs.cn');
expect(response.status()).toBe(200);
});
查看更多关于响应拦截的信息。
🌐 Read more about response interception.
新的 HTML 报告器
🌐 New HTML reporter
试用新的 HTML 报告工具,可以在 playwright.config.ts 文件中使用 --reporter=html 或 reporter 条目:
🌐 Try it out new HTML reporter with either --reporter=html or a reporter entry in playwright.config.ts file:
$ npx playwright test --reporter=html
HTML 报告器拥有有关测试及其失败的所有信息,包括表面痕迹和图片伪影。
🌐 The HTML reporter has all the information about tests and their failures, including surfacing trace and image artifacts.

查看更多关于我们的报告器的信息。
🌐 Read more about our reporters.
🎭 Playwright库
🌐 🎭 Playwright Library
locator.waitFor
等待定位符解析为具有特定状态的单一元素。默认为“state: 'visible'”。
🌐 Wait for a locator to resolve to a single element with a given state. Defaults to the state: 'visible'.
使用列表时特别方便:
🌐 Comes especially handy when working with lists:
import { test, expect } from '@playwright/test';
test('context fetch', async ({ page }) => {
const completeness = page.locator('text=Success');
await completeness.waitFor();
expect(await page.screenshot()).toMatchSnapshot('screen.png');
});
阅读更多关于 locator.waitFor() 的内容。
🌐 Read more about locator.waitFor().
Docker 对 Arm64 的支持
🌐 Docker support for Arm64
Playwright Docker 镜像现已发布适用于 Arm64 的版本,因此可以在 Apple Silicon 上使用。
🌐 Playwright Docker image is now published for Arm64 so it can be used on Apple Silicon.
查看更多关于 Docker 集成 的信息。
🌐 Read more about Docker integration.
🎭 Playwright追踪器
🌐 🎭 Playwright Trace Viewer
- 跟踪查看器中的 Web 优先断言
- 使用
npx playwright show-trace运行跟踪查看器,并将跟踪文件拖到跟踪查看器 PWA 中 - API 测试与跟踪查看器集成
- 更好地对行动目标进行视觉归因
查看更多关于 Trace Viewer 的信息。
🌐 Read more about Trace Viewer.
浏览器版本
🌐 Browser Versions
- Chromium 97.0.4666.0
- 火狐浏览器 93.0
- 网络工具包 15.4
此版本的 Playwright 还针对以下稳定通道进行了测试:
🌐 This version of Playwright was also tested against the following stable channels:
- 谷歌浏览器 94
- 微软 Edge 94
1.15 版本
🌐 Version 1.15
🎭 Playwright库
🌐 🎭 Playwright Library
🖱️ 鼠标滚轮
🌐 🖱️ Mouse Wheel
通过使用 mouse.wheel(),你现在可以进行垂直或水平滚动。
🌐 By using mouse.wheel() you are now able to scroll vertically or horizontally.
📜 新的 Headers API
🌐 📜 New Headers API
以前无法获取响应的多个头部值。现在可以实现,并且提供了额外的辅助函数:
🌐 Previously it was not possible to get multiple header values of a response. This is now possible and additional helper functions are available:
- request.allHeaders()
- request.headersArray()
- request.headerValue()
- response.allHeaders()
- response.headersArray()
- response.headerValue()
- response.headerValues()
🌈 强制颜色模拟
🌐 🌈 Forced-Colors emulation
现在可以通过在 browser.newContext() 中传入 forced-colors CSS 媒体特性或调用 page.emulateMedia() 来模拟它。
🌐 Its now possible to emulate the forced-colors CSS media feature by passing it in the browser.newContext() or calling page.emulateMedia().
新 API
🌐 New APIs
- page.route() 接受新的
times选项,用于指定此路由应匹配的次数。 - page.setChecked() 和 locator.setChecked() 用于设置复选框的选中状态。
- request.sizes() 返回给定 HTTP 请求的资源大小信息。
- tracing.startChunk() - 开始一个新的追踪区块。
- tracing.stopChunk() - 停止新的追踪区块。
🎭 Playwright测试
🌐 🎭 Playwright Test
🤝 test.parallel() 在同一文件中并行运行测试
🌐 🤝 test.parallel() run tests in the same file in parallel
test.describe.parallel('group', () => {
test('runs in parallel 1', async ({ page }) => {
});
test('runs in parallel 2', async ({ page }) => {
});
});
默认情况下,单个文件中的测试会按顺序运行。如果你在单个文件中有许多独立的测试,现在可以使用 test.describe.parallel(title, callback) 并行运行它们。
🌐 By default, tests in a single file are run in order. If you have many independent tests in a single file, you can now run them in parallel with test.describe.parallel(title, callback).
🛠 添加 --debug CLI 标志
🌐 🛠 Add --debug CLI flag
通过使用 npx playwright test --debug,它将为你启用 Playwright Inspector 来调试你的测试。
🌐 By using npx playwright test --debug it will enable the Playwright Inspector for you to debug your tests.
浏览器版本
🌐 Browser Versions
- Chromium 96.0.4641.0
- 火狐浏览器 92.0
- 网络工具包 15.0
1.14 版本
🌐 Version 1.14
🎭 Playwright库
🌐 🎭 Playwright Library
⚡️ 新的“严格”模式
🌐 ⚡️ New "strict" mode
选择器歧义是自动化测试中常见的问题。“严格”模式确保你的选择器指向单个元素,否则会抛出异常。
🌐 Selector ambiguity is a common problem in automation testing. "strict" mode ensures that your selector points to a single element and throws otherwise.
在调用操作时传入 strict: true 以选择加入。
🌐 Pass strict: true into your action calls to opt in.
// This will throw if you have more than one button!
await page.click('button', { strict: true });
📍 新 定位器 API
🌐 📍 New Locators API
定位器表示页面上元素的视图。它包含足够的逻辑来在任何给定时刻获取该元素。
🌐 Locator represents a view to the element(s) on the page. It captures the logic sufficient to retrieve the element at any given moment.
Locator 和 ElementHandle 的区别在于,后者指向特定的元素,而 Locator 捕捉的是如何获取该元素的逻辑。
🌐 The difference between the Locator and ElementHandle is that the latter points to a particular element, while Locator captures the logic of how to retrieve that element.
另外,定位器默认是**“严格”**的!
🌐 Also, locators are "strict" by default!
const locator = page.locator('button');
await locator.click();
在文档中了解更多信息。
🌐 Learn more in the documentation.
🧩 实验性 React 和 Vue 选择器引擎
🌐 🧩 Experimental React and Vue selector engines
React 和 Vue 选择器允许通过组件名称和/或属性值来选择元素。其语法与属性选择器非常相似,并且支持所有属性选择器操作符。
🌐 React and Vue selectors allow selecting elements by its component name and/or property values. The syntax is very similar to attribute selectors and supports all attribute selector operators.
await page.locator('_react=SubmitButton[enabled=true]').click();
await page.locator('_vue=submit-button[enabled=true]').click();
在React 选择器文档和Vue 选择器文档中了解更多信息。
🌐 Learn more in the react selectors documentation and the vue selectors documentation.
✨ 新的 nth 和 visible 选择器引擎
🌐 ✨ New nth and visible selector engines
// select the first button among all buttons
await button.click('button >> nth=0');
// or if you are using locators, you can use first(), nth() and last()
await page.locator('button').first().click();
// click a visible button
await button.click('button >> visible=true');
🎭 Playwright测试
🌐 🎭 Playwright Test
✅ 网络优先断言
🌐 ✅ Web-First Assertions
expect 现在支持许多新的面向网络的断言。
考虑以下示例:
🌐 Consider the following example:
await expect(page.locator('.status')).toHaveText('Submitted');
Playwright 测试将会重新测试带有选择器 .status 的节点,直到获取到的节点包含 "Submitted" 文本。它会反复重新获取节点并进行检查,直到条件满足或超时为止。你可以选择传递这个超时值,或者在测试配置中通过 testProject.expect 值进行一次性配置。
🌐 Playwright Test will be re-testing the node with the selector .status until fetched Node has the "Submitted" text. It will be re-fetching the node and checking it over and over, until the condition is met or until the timeout is reached. You can either pass this timeout or configure it once via the testProject.expect value in test config.
默认情况下,未设置断言超时,因此它将永远等待,直到整个测试超时。
🌐 By default, the timeout for assertions is not set, so it'll wait forever, until the whole test times out.
所有新断言列表:
🌐 List of all new assertions:
expect(locator).toBeChecked()expect(locator).toBeDisabled()expect(locator).toBeEditable()expect(locator).toBeEmpty()expect(locator).toBeEnabled()expect(locator).toBeFocused()expect(locator).toBeHidden()expect(locator).toBeVisible()expect(locator).toContainText(text, options?)expect(locator).toHaveAttribute(name, value)expect(locator).toHaveClass(expected)expect(locator).toHaveCount(count)expect(locator).toHaveCSS(name, value)expect(locator).toHaveId(id)expect(locator).toHaveJSProperty(name, value)expect(locator).toHaveText(expected, options)expect(page).toHaveTitle(title)expect(page).toHaveURL(url)expect(locator).toHaveValue(value)
⛓ 使用 describe.serial 的串行模式
🌐 ⛓ Serial mode with describe.serial
声明一组应始终按顺序运行的测试。如果其中一个测试失败,则所有后续测试将被跳过。组中的所有测试将一起重试。
🌐 Declares a group of tests that should always be run serially. If one of the tests fails, all subsequent tests are skipped. All tests in a group are retried together.
test.describe.serial('group', () => {
test('runs first', async ({ page }) => { /* ... */ });
test('runs second', async ({ page }) => { /* ... */ });
});
在文档中了解更多信息。
🌐 Learn more in the documentation.
🐾 使用 test.step 的 Steps API
🌐 🐾 Steps API with test.step
使用“test.step()”接口将长测试拆分成多个步骤:
🌐 Split long tests into multiple steps using test.step() API:
import { test, expect } from '@playwright/test';
test('test', async ({ page }) => {
await test.step('Log in', async () => {
// ...
});
await test.step('news feed', async () => {
// ...
});
});
步骤信息在报告器 API 中公开。
🌐 Step information is exposed in reporters API.
🌎 在运行测试之前启动网络服务器
🌐 🌎 Launch web server before running tests
在测试期间启动服务器,请在配置文件中使用 webServer 选项。服务器将在指定的 URL 可用之前等待,然后在创建上下文时,该 URL 将作为 baseURL 传递给 Playwright。
🌐 To launch a server during the tests, use the webServer option in the configuration file. The server will wait for a given url to be available before running the tests, and the url will be passed over to Playwright as a baseURL when creating a context.
import { defineConfig } from '@playwright/test';
export default defineConfig({
webServer: {
command: 'npm run start', // command to launch
url: 'http://127.0.0.1:3000', // url to await for
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
},
});
在文档中了解更多信息。
🌐 Learn more in the documentation.
浏览器版本
🌐 Browser Versions
- Chromium 94.0.4595.0
- 火狐浏览器 91.0
- 网络工具包 15.0
1.13 版本
🌐 Version 1.13
Playwright 测试
🌐 Playwright Test
- ⚡️ 介绍 Reporter API,它已经被用来创建一个 Allure Playwright 报告器。
- ⛺️ 新的
baseURL测试工具,以支持测试中的相对路径。
Playwright
- 🖖 通过 page.dragAndDrop() API 提供的编程拖放支持。
- 🔎 增强型 HAR,包含请求和响应的体积信息。可通过在 browser.newContext() 中使用
recordHar选项来使用。
工具
🌐 Tools
- Playwright跟踪查看器现在显示参数、返回值和
console.log()调用。 - Playwright Inspector 可以生成 Playwright Test 测试。
新的和大修的指南
🌐 New and Overhauled Guides
浏览器版本
🌐 Browser Versions
- Chromium 93.0.4576.0
- 火狐浏览器 90.0
- 网络工具包 14.2
新 Playwright API
🌐 New Playwright APIs
- browser.newContext() 和 browser.newPage() 中的新
baseURL选项 - response.securityDetails() and response.serverAddr()
- page.dragAndDrop() and frame.dragAndDrop()
- download.cancel()
- page.inputValue(), frame.inputValue() and elementHandle.inputValue()
- page.fill()、frame.fill() 和 elementHandle.fill() 中的新
force选项 - page.selectOption()、frame.selectOption() 和 elementHandle.selectOption() 中的新
force选项
1.12 版本
🌐 Version 1.12
⚡️ 推出 Playwright 测试
🌐 ⚡️ Introducing Playwright Test
Playwright Test 是由 Playwright 团队从零开发的 全新测试运行器,专门用于满足端到端测试的需求:
- 在所有浏览器上运行测试。
- 并行执行测试。
- 享受开箱即用的上下文隔离和合理的默认设置。
- 捕获失败时的视频、屏幕截图和其他工件。
- 将 POM 集成为可扩展的装置。
安装:
🌐 Installation:
npm i -D @playwright/test
简单测试 tests/foo.spec.ts:
🌐 Simple test tests/foo.spec.ts:
import { test, expect } from '@playwright/test';
test('basic test', async ({ page }) => {
await page.goto('https://playwright.nodejs.cn/');
const name = await page.innerText('.navbar__title');
expect(name).toBe('Playwright');
});
运行:
🌐 Running:
npx playwright test
👉 在 Playwright Test 文档 中阅读更多内容。
🧟♂️ 推出 Playwright 跟踪查看器
🌐 🧟♂️ Introducing Playwright Trace Viewer
Playwright Trace Viewer 是一个新的图形界面工具,可帮助在脚本运行后探索已记录的 Playwright 跟踪。Playwright 跟踪让你可以检查:
- 每个 Playwright 操作之前和之后的页面 DOM
- 每个 Playwright 操作之前和之后的页面渲染
- 脚本执行期间的浏览器网络
使用新的 browserContext.tracing API 记录跟踪:
🌐 Traces are recorded using the new browserContext.tracing API:
const browser = await chromium.launch();
const context = await browser.newContext();
// Start tracing before creating / navigating a page.
await context.tracing.start({ screenshots: true, snapshots: true });
const page = await context.newPage();
await page.goto('https://playwright.nodejs.cn');
// Stop tracing and export it into a zip archive.
await context.tracing.stop({ path: 'trace.zip' });
稍后使用 Playwright CLI 检查痕迹:
🌐 Traces are examined later with the Playwright CLI:
npx playwright show-trace trace.zip
这将打开以下 GUI:
🌐 That will open the following GUI:

👉 在 追踪查看器文档 中阅读更多内容。
浏览器版本
🌐 Browser Versions
- Chromium 93.0.4530.0
- 火狐浏览器 89.0
- 网络工具包 14.2
此版本的 Playwright 还针对以下稳定通道进行了测试:
🌐 This version of Playwright was also tested against the following stable channels:
- 谷歌浏览器 91
- 微软 Edge 91
新 API
🌐 New APIs
reducedMotion选项在 page.emulateMedia()、browserType.launchPersistentContext()、browser.newContext() 和 browser.newPage() 中- browserContext.on('request')
- browserContext.on('requestfailed')
- browserContext.on('requestfinished')
- browserContext.on('response')
- browserType.launch() 和 browserType.launchPersistentContext() 中的
tracesDir选项 - 新的 browserContext.tracing API 命名空间
- 新的 download.page() 方法
1.11 版本
🌐 Version 1.11
🎥 新视频:Playwright:面向现代网页的新测试自动化框架 (幻灯片)
- 我们谈论了 Playwright
- 展示了幕后的工程工作
- 展示了带有新功能的实时演示 ✨
- 特别感谢 applitools 举办此次活动并邀请我们!
浏览器版本
🌐 Browser Versions
- Chromium 92.0.4498.0
- 火狐浏览器 89.0b6
- 网络工具包 14.2
新 API
🌐 New APIs
- 在 API 中的方法(例如 page.waitForRequest() 等)中支持 异步谓词
- 新的模拟设备:Galaxy S8、Galaxy S9+、Galaxy Tab S4、Pixel 3、Pixel 4
- 新方法:
- page.waitForURL() 用于等待导航到 URL
- video.delete() 和 video.saveAs() 来管理屏幕录制
- 新选项:
- browser.newContext() 方法中的
screen选项,用于模拟window.screen尺寸 - page.check() 和 page.uncheck() 方法中的
position选项 trial选项可在 page.check()、page.uncheck()、page.click()、page.dblclick()、page.hover() 和 page.tap() 中进行干运行操作
- browser.newContext() 方法中的
1.10 版本
🌐 Version 1.10
- Java 版 Playwright v1.10 现已稳定!
- 使用 新渠道 API 在 Google Chrome 和 Microsoft Edge 稳定版通道上运行 Playwright。
- Chromium 在 Mac 和 Windows 上截屏非常快速。
打包的浏览器版本
🌐 Bundled Browser Versions
- Chromium 90.0.4430.0
- 火狐浏览器 87.0b10
- 网络工具包 14.2
此版本的 Playwright 还针对以下稳定通道进行了测试:
🌐 This version of Playwright was also tested against the following stable channels:
- 谷歌浏览器 89
- 微软 Edge 89
新 API
🌐 New APIs
- browserType.launch() now accepts the new
'channel'option. Read more in our documentation.
1.9 版本
🌐 Version 1.9
- Playwright Inspector 是一个用于编写和调试测试的新图形界面工具。
- 逐行调试你的 Playwright 脚本,支持播放、暂停和逐步执行。
- 通过记录用户操作来编写新脚本。
- 通过悬停在元素上为你的脚本生成元素选择器。
- 设置
PWDEBUG=1环境变量以启动检查器
- 暂停脚本执行 使用 page.pause() 在有界面模式下。暂停页面会启动 Playwright Inspector 进行调试。
- 新的 has-text 伪类 用于 CSS 选择器。
:has-text("example")匹配任何在其内部(可能在子元素或后代元素中)包含"example"的元素。查看 更多示例。 - 页面对话框现在在执行期间会自动关闭,除非配置了
dialog事件的监听器。了解更多。 - Python 的 Playwright 现已稳定,提供符合习惯的蛇形命名 API,并提供预构建的 Docker 镜像 用于在 CI/CD 中运行测试。
浏览器版本
🌐 Browser Versions
- Chromium 90.0.4421.0
- 火狐浏览器 86.0b10
- 网络工具包 14.1
新 API
🌐 New APIs
1.8 版本
🌐 Version 1.8
-
使用
:left-of()、:right-of()、:above()和:below()基于布局选择元素。 -
Playwright 现在包括 命令行接口,原先的 playwright-cli。
npx playwright --help -
page.selectOption() 现在会等待选项出现。
-
用于断言元素状态的新方法,如page.isEditable()。
新 API
🌐 New APIs
- elementHandle.isChecked().
- elementHandle.isDisabled().
- elementHandle.isEditable().
- elementHandle.isEnabled().
- elementHandle.isHidden().
- elementHandle.isVisible().
- page.isChecked().
- page.isDisabled().
- page.isEditable().
- page.isEnabled().
- page.isHidden().
- page.isVisible().
- elementHandle.waitForElementState() 中的新选项
'editable'。
浏览器版本
🌐 Browser Versions
- Chromium 90.0.4392.0
- 火狐浏览器 85.0b5
- 网络工具包 14.1
1.7 版本
🌐 Version 1.7
- 新的 Java SDK:Playwright for Java 现在与 JavaScript、Python 和 .NET 绑定 相当。
- 浏览器存储 API:新的便捷 API,用于保存和加载浏览器存储状态(Cookie、本地存储),以简化带有身份验证的自动化场景。
- 新的 CSS 选择器:我们收到了你对更灵活选择器的反馈,因此重新设计了选择器的实现。Playwright 1.7 引入了新的 CSS 扩展,并且未来还会有更多更新。
- 新网站:位于 playwright.dev 的文档网站已更新,现在使用 Docusaurus 构建。
- 支持 Apple Silicon:WebKit 和 Chromium 的 Playwright 浏览器二进制文件现在已为 Apple Silicon 构建。
新 API
🌐 New APIs
- browserContext.storageState() 用于获取当前状态以便以后重用。
- 在 browser.newContext() 和 browser.newPage() 中使用
storageState选项来设置浏览器上下文状态。
浏览器版本
🌐 Browser Versions
- Chromium 89.0.4344.0
- 火狐浏览器 84.0b9
- 网络工具包 14.1