跳到主要内容

版本发布说明

版本 1.52

亮点功能

  • 新增方法 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.dev"
    `);

测试运行器

  • 新增属性 testProject.workers 允许为测试项目指定并发工作进程数。全局限制属性 testConfig.workers 仍然适用。
  • 新增 testConfig.failOnFlakyTests 选项,当检测到任何不稳定的测试时会使测试运行失败,类似于 --fail-on-flaky-tests。这对于 CI/CD 环境非常有用,您可以在部署前确保所有测试都是稳定的。
  • 新增属性 testResult.annotations 包含每次测试重试的注解信息。

杂项更新

  • apiRequest.newContext() 中新增 maxRedirects 选项,用于控制最大重定向次数。
  • locator.ariaSnapshot() 中新增 ref 选项,可为快照中的每个元素生成引用标识,后续可用于定位元素。
  • HTML 报告器现在支持通过 !@my-tag!my-file.spec.ts!p:my-project 语法进行反向过滤

重大变更

  • page.route() 等方法中使用通配符 URL 模式时,不再支持 ?[] 字符。建议改用正则表达式替代。
  • 方法 route.continue() 不再允许覆盖 Cookie 请求头。如果提供了 Cookie 头,它将被忽略,而是从浏览器的 Cookie 存储中加载。如需设置自定义 Cookie,请使用 browserContext.addCookies()
  • macOS 13 现已弃用,将不再接收 WebKit 更新。请升级到更新的 macOS 版本以继续获得最新的 WebKit 改进。

浏览器版本

  • Chromium 136.0.7103.25
  • Mozilla Firefox 137.0
  • WebKit 18.4

此版本还针对以下稳定渠道进行了测试:

  • Google Chrome 135
  • Microsoft Edge 135

版本 1.51

StorageState 支持 indexedDB

  • 新增的 indexedDB 选项可用于 browserContext.storageState(),允许保存和恢复 IndexedDB 内容。当你的应用使用 IndexedDB API 存储认证令牌(如 Firebase Authentication)时非常有用。

    以下是遵循 认证指南 的示例:

    tests/auth.setup.ts
    import { 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('/');
    // ... 执行认证步骤 ...

    // 确保保存 indexedDB
    await page.context().storageState({ path: authFile, indexedDB: true });
    });

复制为提示

在 HTML 报告、追踪查看器和 UI 模式中新增了"复制提示"按钮。点击可复制预填充的 LLM 提示,其中包含错误信息和修复错误的有用上下文。

复制提示

过滤可见元素

locator.filter() 新增了 visible 选项,允许只匹配可见元素。

example.spec.ts
test('some test', async ({ page }) => {
// 忽略不可见的待办事项项
const todoItems = page.getByTestId('todo-item').filter({ visible: true });
// 检查正好有3个可见项
await expect(todoItems).toHaveCount(3);
});

HTML 报告中的 Git 信息

设置选项 testConfig.captureGitInfo 可以将 Git 信息捕获到 testConfig.metadata 中。

playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
captureGitInfo: { commit: true, diff: true }
});

当信息可用时,HTML 报告将显示这些内容:

报告中的 Git 信息

测试步骤改进

现在测试步骤中可以使用新的 TestStepInfo 对象。您可以在步骤中添加附件或在某些条件下跳过该步骤。

test('某个测试', async ({ page, isMobile }) => {
// 注意新的 "step" 参数:
await test.step('这是我的步骤', async step => {
step.skip(isMobile, '在移动端布局中不相关');

// ...
await step.attach('我的附件', { body: '一些文本' });
// ...
});
});

其他改进

浏览器版本

  • Chromium 134.0.6998.35
  • Mozilla Firefox 135.0
  • WebKit 18.4

此版本还针对以下稳定版渠道进行了测试:

  • Google Chrome 133
  • Microsoft Edge 133

版本 1.50

测试运行器

  • 新增选项 timeout 允许为单个测试步骤指定最大运行时间。超时的步骤会导致测试执行失败。

    test('some test', async ({ page }) => {
    await test.step('a step', async () => {
    // 这个步骤可以独立于测试单独设置超时
    }, { timeout: 1000 });
    });
  • 新增方法 test.step.skip() 用于禁用测试步骤的执行。

    test('some test', async ({ page }) => {
    await test.step('before running step', async () => {
    // 正常步骤
    });

    await test.step.skip('not yet ready', async () => {
    // 这个步骤会被跳过
    });

    await test.step('after running step', async () => {
    // 即使前一个步骤被跳过,这个步骤仍会执行
    });
    });
  • 扩展了 expect(locator).toMatchAriaSnapshot() 功能,允许将 aria 快照存储在单独的 YAML 文件中。

  • 新增方法 expect(locator).toHaveAccessibleErrorMessage() 用于断言定位器指向具有指定 aria errormessage 的元素。

  • 选项 testConfig.updateSnapshots 新增了配置枚举 changedchanged 仅更新已变更的快照,而 all 现在会更新所有快照,无论是否存在差异。

  • 新增选项 testConfig.updateSourceMethod 定义当配置了 testConfig.updateSnapshots 时更新源代码的方式。在现有的创建补丁文件的 patch 模式基础上,新增了将更改写入源代码的 overwrite3-way 模式。

    npx playwright test --update-snapshots=changed --update-source-method=3way
  • 选项 testConfig.webServer 新增了 gracefulShutdown 字段,用于指定默认 SIGKILL 之外的其他进程终止信号。

  • 从报告器 API 中暴露了 testStep.attachments,允许检索该步骤创建的所有附件。

  • testConfig.expect 配置中,为 toHaveScreenshottoMatchAriaSnapshot 断言新增了 pathTemplate 选项。

UI 更新

  • 更新了默认 HTML 报告器以改进附件显示效果
  • 在代码生成器中新增按钮用于选取元素生成 ARIA 快照
  • 现在在追踪记录中会显示更多操作 API 调用的详细信息(例如按下的按键)
  • 追踪记录中显示 canvas 内容容易出错。现已默认禁用此功能,可通过 UI 设置中的 显示 canvas 内容 选项启用
  • 调用网络 面板现在会显示额外的时间信息

重大变更

浏览器版本

  • Chromium 133.0.6943.16
  • Mozilla Firefox 134.0
  • WebKit 18.2

此版本还针对以下稳定版渠道进行了测试:

  • Google Chrome 132
  • Microsoft Edge 132

版本 1.49

ARIA 快照

新增断言方法 expect(locator).toMatchAriaSnapshot() 通过对比预期的无障碍树(以 YAML 格式表示)来验证页面结构。

await page.goto('https://playwright.dev');
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"
`);

您可以通过测试生成器生成此断言,并使用 --update-snapshots 命令行参数更新预期的快照。

了解更多信息,请参阅 ARIA 快照指南

测试运行器

重大变更:chromemsedge 渠道切换至全新无头模式

如果您在 playwright.config.ts 中使用以下任一渠道,此变更将影响您:

  • chromechrome-devchrome-betachrome-canary
  • msedgemsedge-devmsedge-betamsedge-canary

我需要做什么?

升级到 Playwright v1.49 后,运行您的测试套件。如果测试通过,则无需任何操作。如果失败,您可能需要更新快照,并调整与 PDF 查看器和浏览器扩展相关的测试代码。更多详情请参阅 issue #33566

其他重大变更

  • 将不再为 Ubuntu 20.04 和 Debian 11 提供 WebKit 更新。建议您将操作系统升级至更高版本。
  • @playwright/experimental-ct-vue2 将不再更新。
  • @playwright/experimental-ct-solid 将不再更新。

尝试新版 Chromium 无头模式

您可以通过使用 'chromium' 渠道来启用新的无头模式。正如 Chrome 官方文档所述

新版无头模式是真正的 Chrome 浏览器,因此更真实、更可靠,并提供更多功能。这使其更适合高精度的端到端 Web 应用测试或浏览器扩展测试。

关于可能遇到的问题列表及 Chromium 无头模式的更多详情,请参阅 issue #33566。如果您在启用后遇到任何问题,请提交 issue。

import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'], channel: 'chromium' },
},
],
});

杂项更新

  • 快照中的 <canvas> 元素现在会显示预览图
  • 新增 tracing.group() 方法,用于在追踪记录中可视化分组操作
  • Playwright Docker 镜像已从 Node.js v20 切换至 Node.js v22 LTS 版本

浏览器版本

  • Chromium 131.0.6778.33
  • Mozilla Firefox 132.0
  • WebKit 18.2

此版本还通过了以下稳定版浏览器的测试:

  • Google Chrome 130
  • Microsoft Edge 130

版本 1.48

WebSocket 路由

新增方法 page.routeWebSocket()browserContext.routeWebSocket(),可以拦截、修改和模拟页面中发起的 WebSocket 连接。以下是一个简单示例,通过响应 "request" 返回 "response" 来模拟 WebSocket 通信:

await page.routeWebSocket('/ws', ws => {
ws.onMessage(message => {
if (message === 'request')
ws.send('response');
});
});

更多详情请参阅 WebSocketRoute

界面更新

  • HTML 报告中新增了用于复制注释和测试位置的"复制"按钮
  • 不再在报告和追踪查看器中显示 route.fulfill() 等路由方法调用,相关网络请求路由信息可在网络标签页查看
  • 网络标签页中的请求新增了"复制为 cURL"和"复制为 fetch"按钮

杂项更新

浏览器版本

  • Chromium 130.0.6723.19
  • Mozilla Firefox 130.0
  • WebKit 18.0

此版本还针对以下稳定渠道进行了测试:

  • Google Chrome 129
  • Microsoft Edge 129

版本 1.47

网络面板改进

UI 模式和追踪查看器中的网络面板有多项改进:

  • 支持按资源类型和 URL 过滤
  • 更优的查询字符串参数显示
  • 字体资源预览功能

网络面板新增过滤器

--tsconfig 命令行选项

默认情况下,Playwright 会使用启发式方法为每个导入文件查找最近的 tsconfig。现在您可以在命令行中指定单个 tsconfig 文件,Playwright 将用于所有导入文件(不仅限于测试文件):

# 传递特定的 tsconfig 文件
npx playwright test --tsconfig tsconfig.test.json

APIRequestContext 现在支持 URLSearchParamsstring 作为查询参数

现在你可以向 APIRequestContext 传递 URLSearchParamsstring 作为查询参数:

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 // 或者作为字符串传递: 'userId=1'
}
);
// ...
});

杂项更新

  • mcr.microsoft.com/playwright:v1.47.0 现在提供基于 Ubuntu 24.04 Noble 的 Playwright 镜像。如需使用基于 22.04 jammy 的镜像,请改用 mcr.microsoft.com/playwright:v1.47.0-jammy
  • 新增 behaviorbehaviorbehavior 选项,用于等待正在执行的事件监听器完成
  • 现在可以通过传递 clientCertificates.certclientCertificates.key 作为缓冲区(而非文件路径)来从内存中传递 TLS 客户端证书
  • 现在可以在 HTML 报告中以新标签页打开 text/html 内容类型的附件。这对于在 Playwright 测试报告中包含第三方报告或其他 HTML 内容并分发给团队非常有用
  • locator.selectOption() 中的 noWaitAfter 选项已被弃用
  • 我们收到关于 Webkit 中 WebGL 在 GitHub Actions macos-13 上运行异常的反馈。建议将 GitHub Actions 升级至 macos-14

浏览器版本

  • Chromium 129.0.6668.29
  • Mozilla Firefox 130.0
  • WebKit 18.0

此版本还针对以下稳定渠道进行了测试:

  • Google Chrome 128
  • Microsoft Edge 128

版本 1.46

TLS 客户端证书

Playwright 现在支持提供客户端证书,以便服务器能够按照 TLS 客户端认证规范进行验证。

以下代码片段为 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',
}],
},
// ...
});

您也可以为特定的 测试项目 提供客户端证书,或者作为 browser.newContext()apiRequest.newContext() 方法的参数。

--only-changed 命令行选项

新增的 CLI 选项 --only-changed 只会运行自上次 git 提交或特定 git "ref" 以来发生变更的测试文件。该选项也会运行所有引用了变更文件的测试文件。

# 仅运行有未提交变更的测试文件
npx playwright test --only-changed


# 仅运行相对于 "main" 分支有变更的测试文件
npx playwright test --only-changed=main

组件测试:新增 router 固定装置

本次发布引入了一个实验性的 router 固定装置,用于在组件测试中拦截和处理网络请求。该装置有两种使用方式:

  • 调用 router.route(url, handler),其行为类似于 page.route()
  • 调用 router.use(handlers) 并传入 MSW 库 的请求处理器

以下是在测试中复用现有 MSW 处理器的示例:

import { handlers } from '@src/mocks/handlers';

test.beforeEach(async ({ router }) => {
// 在每个测试前安装通用处理器
await router.use(...handlers);
});

test('示例测试', async ({ mount }) => {
// 正常进行测试,你的处理器已生效
// ...
});

该固定装置仅在 组件测试 中可用。

UI 模式/追踪查看器更新

  • 测试注解现在会显示在 UI 模式中
  • 文本附件的内容现在会在附件面板内联渲染
  • 新增设置选项用于显示/隐藏路由操作,如 route.continue()
  • 网络详情标签页现在会显示请求方法和状态码
  • 新增按钮可将源文件位置复制到剪贴板
  • 元数据面板现在会显示 baseURL

其他改进

浏览器版本

  • Chromium 128.0.6613.18
  • Mozilla Firefox 128.0
  • WebKit 18.0

此版本还针对以下稳定渠道进行了测试:

  • Google Chrome 127
  • Microsoft Edge 127

版本 1.45

时钟控制

使用全新的 Clock API 可以在测试中操纵和控制时间,以验证与时间相关的行为。该 API 涵盖了许多常见场景,包括:

  • 使用预设时间进行测试
  • 保持时间与计时器的一致性
  • 监控不活动状态
  • 手动推进时间
// 初始化时钟并让页面自然加载
await page.clock.install({ time: new Date('2024-02-02T08:00:00') });
await page.goto('http://localhost:3333');

// 模拟用户合上笔记本盖子并在上午10点重新打开
// 当时间到达该点时暂停
await page.clock.pauseAt(new Date('2024-02-02T10:00:00'));

// 断言页面状态
await expect(page.getByTestId('current-time')).toHaveText('2/2/2024, 10:00:00 AM');

// 再次合上笔记本盖子并在上午10:30打开
await page.clock.fastForward('30:00');
await expect(page.getByTestId('current-time')).toHaveText('2/2/2024, 10:30:00 AM');

更多详情请参阅 时钟控制指南

测试运行器

  • 新增 CLI 选项 --fail-on-flaky-tests,当出现任何不稳定的测试时将退出码设为 1。请注意,默认情况下当所有失败的测试在重试后恢复时,测试运行器会以代码 0 退出。使用此选项后,在这种情况下测试运行将失败。

  • 新增环境变量 PLAYWRIGHT_FORCE_TTY 控制内置的 listlinedot 报告器是否假设为实时终端。例如,当你的 CI 环境无法很好地处理 ANSI 控制序列时,这可以用来禁用 tty 行为。或者,即使没有实时终端,你也可以启用 tty 行为,前提是你计划对输出进行后处理并处理控制序列。

    # 避免输出 ANSI 控制序列的 TTY 特性
    PLAYWRIGHT_FORCE_TTY=0 npx playwright test

启用 TTY 功能,假设终端宽度为 80

PLAYWRIGHT_FORCE_TTY=80 npx playwright test


- 新增选项 [testConfig.respectGitIgnore](/api/class-testconfig.mdx#test-config-respect-git-ignore) 和 [testProject.respectGitIgnore](/api/class-testproject.mdx#test-project-respect-git-ignore) 用于控制是否排除匹配 `.gitignore` 模式的文件在搜索测试时。
- 自定义 expect 匹配器现在支持新属性 `timeout`。该属性会考虑 `playwright.config.ts` 和 `expect.configure()` 的配置。

```js
import { expect as baseExpect } from '@playwright/test';

export const expect = baseExpect.extend({
async toHaveAmount(locator: Locator, expected: number, options?: { timeout?: number }) {
// 当未指定 timeout 选项时,使用配置中的超时时间
const timeout = options?.timeout ?? this.timeout;
// ... 实现断言逻辑 ...
},
});

杂项更新

  • locator.setInputFiles() 方法现在支持为 <input type=file webkitdirectory> 元素上传整个目录。

    await page.getByLabel('上传目录').setInputFiles(path.join(__dirname, 'mydir'));
  • 多个方法如 locator.click()locator.press() 现在支持 ControlOrMeta 修饰键。该键在 macOS 上映射为 Meta 键,在 Windows 和 Linux 上映射为 Control 键。

    // 按下通用的键盘快捷键 Control+S 或 Meta+S 来触发"保存"操作
    await page.keyboard.press('ControlOrMeta+S');
  • apiRequest.newContext() 新增了 httpCredentials.send 属性,允许始终发送 Authorization 头或仅在收到 401 Unauthorized 响应时发送。

  • apiRequestContext.dispose() 新增了 reason 选项,该原因会被包含在因上下文销毁而中断的正在进行的操作的错误信息中。

  • browserType.launchServer() 新增了 host 选项,允许在特定地址而非未指定的 0.0.0.0 上接受 WebSocket 连接。

  • Playwright 现在支持在 Ubuntu 24.04 上运行 Chromium、Firefox 和 WebKit。

  • v1.45 是最后一个为 macOS 12 Monterey 提供 WebKit 更新的版本。如需继续使用最新的 WebKit,请升级 macOS 系统。

浏览器版本

  • Chromium 127.0.6533.5
  • Mozilla Firefox 127.0
  • WebKit 17.4

此版本也已针对以下稳定渠道进行测试:

  • Google Chrome 126
  • Microsoft Edge 126

版本 1.44

新 API

无障碍断言

  • 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');

定位器处理器

const locator = page.getByText('This interstitial covers the button');
await page.addLocatorHandler(locator, async overlay => {
await overlay.locator('#close').click();
}, { times: 3, noWaitAfter: true });
// 运行可能被覆盖层中断的测试
// ...
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 中的全局配置或 testProject.expect 中的项目级配置来设置 expect.toPass.intervals 选项。

  • expect(page).toHaveURL(url) 现在支持 ignoreCase 选项

  • testProject.ignoreSnapshots 允许按项目配置是否跳过截图断言。

报告器 API

  • 新方法 suite.entries() 返回子测试套件和测试用例,按声明顺序排列。可以使用 suite.typetestCase.type 来区分列表中的测试用例和套件。
  • Blob 报告器现在允许通过单个选项 outputFile 覆盖报告文件路径。也可以通过 PLAYWRIGHT_BLOB_OUTPUT_FILE 环境变量指定该选项,这在 CI/CD 环境中可能更方便。
  • JUnit 报告器现在支持 includeProjectInTestName 选项。

命令行

  • --last-failed CLI 选项用于仅运行上次运行失败的测试。

    首先运行所有测试:

    $ npx playwright test

    使用 5 个工作线程运行 103 个测试
    ...
    2 个失败
    [chromium] › my-test.spec.ts:8:5 › two ─────────────────────────────────────────────────────────
    [chromium] › my-test.spec.ts:13:5 › three ──────────────────────────────────────────────────────
    101 个通过 (30.0s)

    现在修复失败的测试并使用 --last-failed 选项再次运行 Playwright:

    $ npx playwright test --last-failed

    使用 2 个工作线程运行 2 个测试
    2 个通过 (1.2s)

浏览器版本

  • Chromium 125.0.6422.14
  • Mozilla Firefox 125.0.1
  • WebKit 17.4

此版本还针对以下稳定渠道进行了测试:

  • Google Chrome 124
  • Microsoft Edge 124

版本 1.43

新增 API

  • 方法 browserContext.clearCookies() 现在支持过滤器来仅删除部分 cookies。

    // 清除所有 cookies
    await context.clearCookies();
    // 新增:清除特定名称的 cookies
    await context.clearCookies({ name: 'session-id' });
    // 新增:清除特定域名的 cookies
    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 模式更新

Playwright UI 模式

  • 在测试列表中查看标签
  • 通过输入 @fast 或点击标签本身来按标签过滤
  • 新增快捷键:
    • "F5" 运行测试
    • "Shift F5" 停止运行测试
    • "Ctrl `" 切换测试输出

浏览器版本

  • Chromium 124.0.6367.8
  • Mozilla Firefox 124.0
  • WebKit 17.4

此版本还针对以下稳定版渠道进行了测试:

  • Google Chrome 123
  • Microsoft Edge 123

版本 1.42

新 API

  • 新增方法 page.addLocatorHandler() 用于注册回调函数,当指定元素可见并可能阻塞 Playwright 操作时触发。回调函数可用于消除覆盖层。以下是一个关闭 cookie 弹窗的示例:
// 设置处理器
await page.addLocatorHandler(
page.getByRole('heading', { name: 'Hej! You are in control of your cookies.' }),
async () => {
await page.getByRole('button', { name: 'Accept all' }).click();
});
// 正常编写测试
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();
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('测试客户登录', {
tag: ['@fast', '@login'],
}, async ({ page }) => {
// ...
});

使用 --grep 命令行选项可以只运行带有特定标签的测试。

npx playwright test --grep @fast
  • --project 命令行 参数 现在支持 '*' 通配符:
npx playwright test --project='*mobile*'
test('测试完整报告', {
annotation: [
{ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/23180' },
{ type: 'docs', description: 'https://playwright.dev/docs/test-annotations#tag-tests' },
],
}, async ({ page }) => {
// ...
});

公告

  • ⚠️ 不再支持 Ubuntu 18

浏览器版本

  • Chromium 123.0.6312.4
  • Mozilla Firefox 123.0
  • WebKit 17.4

此版本还针对以下稳定渠道进行了测试:

  • Google Chrome 122
  • Microsoft Edge 123

版本 1.41

新增 API

浏览器版本

  • Chromium 121.0.6167.57
  • Mozilla Firefox 121.0
  • WebKit 17.4

此版本还针对以下稳定渠道进行了测试:

  • Google Chrome 120
  • Microsoft Edge 120

版本 1.40

测试生成器更新

Playwright 测试生成器

新增断言生成工具:

以下是带有断言的生成测试示例:

import { test, expect } from '@playwright/test';

test('test', async ({ page }) => {
await page.goto('https://playwright.dev/');
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

其他变更

浏览器版本

  • Chromium 120.0.6099.28
  • Mozilla Firefox 119.0
  • WebKit 17.4

此版本还针对以下稳定版渠道进行了测试:

  • Google Chrome 119
  • Microsoft Edge 119

版本 1.39

添加自定义匹配器到 expect

您可以通过提供自定义匹配器来扩展 Playwright 断言。这些匹配器将在 expect 对象上可用。

test.spec.ts
import { expect as baseExpect } from '@playwright/test';
export const expect = baseExpect.extend({
async toHaveAmount(locator: Locator, expected: number, options?: { timeout?: number }) {
// ... 查看文档了解如何编写匹配器
},
});

test('pass', async ({ page }) => {
await expect(page.getByTestId('cart')).toHaveAmount(5);
});

查看文档 查看完整示例

合并测试固件

您现在可以合并来自多个文件或模块的测试固件:

fixtures.ts
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);
test.spec.ts
import { test } from './fixtures';

test('passes', async ({ database, page, a11y }) => {
// 使用 database 和 a11y 固件
});

合并自定义 expect 匹配器

现在你可以合并来自多个文件或模块的自定义 expect 匹配器:

fixtures.ts
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);
test.spec.ts
import { test, expect } from './fixtures';

test('测试通过', async ({ page, database }) => {
await expect(database).toHaveDatabaseUser('admin');
await expect(page).toPassA11yAudit();
});

隐藏实现细节:盒装测试步骤

你可以将 test.step() 标记为"盒装",这样其中的错误会指向步骤调用处。

async function login(page) {
await test.step('登录', async () => {
// ...
}, { box: true }); // 注意这里的 "box" 选项
}
错误:等待 expect(locator).toBeVisible() 超时 5000ms
... 错误详情已省略 ...

14 | await page.goto('https://github.com/login');
> 15 | await login(page);
| ^
16 | });

完整示例请参阅 test.step() 文档。

新 API

浏览器版本

  • Chromium 119.0.6045.9
  • Mozilla Firefox 118.0.1
  • WebKit 17.4

此版本还针对以下稳定渠道进行了测试:

  • Google Chrome 118
  • Microsoft Edge 118

版本 1.38

UI 模式更新

Playwright UI 模式

  1. 时间范围缩放功能
  2. 网络面板重新设计

新增 API

弃用项

重大变更:Playwright 不再自动下载浏览器

注意:如果您使用的是 @playwright/test 包,此变更不会影响您。

Playwright 推荐使用 @playwright/test 包并通过 npx playwright install 命令下载浏览器。如果您遵循此建议,则无需做任何改变。

然而,在 v1.38 之前,安装 playwright 包(而非 @playwright/test)会自动下载浏览器。现在这一行为已改变,我们建议通过 npx playwright install 命令显式下载浏览器。

v1.37 及更早版本

playwright 包会在 npm install 过程中下载浏览器,而 @playwright/test 不会。

v1.38 及之后版本

playwright@playwright/test 包都不会在 npm install 过程中下载浏览器。

推荐的迁移方案

npm install 后运行 npx playwright install 下载浏览器。例如,在您的 CI 配置中:

- run: npm ci
- run: npx playwright install --with-deps

替代迁移方案 - 不推荐

添加 @playwright/browser-chromium@playwright/browser-firefox@playwright/browser-webkit 作为依赖项。这些包会在 npm install 过程中下载各自的浏览器。请确保所有 playwright 包的版本保持一致:

// 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"
}
}

浏览器版本

  • Chromium 117.0.5938.62
  • Mozilla Firefox 117.0
  • WebKit 17.0

此版本还针对以下稳定渠道进行了测试:

  • Google Chrome 116
  • Microsoft Edge 116

版本 1.37

新增 npx playwright merge-reports 工具

如果您在多分片环境中运行测试,现在可以使用新的 merge-reports CLI 工具将所有报告合并为单个 HTML 报告(或其他格式报告)。

使用 merge-reports 工具需要以下步骤:

  1. 在 CI 环境中运行时,在配置中添加新的 "blob" 报告器:

    playwright.config.ts
    export default defineConfig({
    testDir: './tests',
    reporter: process.env.CI ? 'blob' : 'html',
    });

    "blob" 报告器会生成包含测试运行所有信息的 ".zip" 文件。

  2. 将所有 "blob" 报告复制到共享位置并运行 npx playwright merge-reports

npx playwright merge-reports --reporter html ./all-blob-reports

了解更多请参阅我们的文档

📚 支持 Debian 12 Bookworm

Playwright 现在支持 Debian 12 Bookworm 系统(x86_64 和 arm64 架构)上的 Chromium、Firefox 和 WebKit。如遇任何问题,请告知我们!

Linux 支持情况如下:

Ubuntu 20.04Ubuntu 22.04Debian 11Debian 12
Chromium
WebKit
Firefox

UI 模式更新

  • UI 模式现在支持项目依赖关系。您可以通过勾选/取消勾选项目列表中的依赖项来控制哪些依赖会被处理。
  • 测试中的控制台日志现在会显示在 Console 标签页中。

浏览器版本

  • Chromium 116.0.5845.82
  • Mozilla Firefox 115.0
  • WebKit 17.0

此版本还针对以下稳定版渠道进行了测试:

  • Google Chrome 115
  • Microsoft Edge 115

版本 1.36

🏝️ 夏季维护版本

浏览器版本

  • Chromium 115.0.5790.75
  • Mozilla Firefox 115.0
  • WebKit 17.0

此版本还针对以下稳定版渠道进行了测试:

  • Google Chrome 114
  • Microsoft Edge 114

版本 1.35

亮点功能

  • UI 模式现已通过 VSCode Playwright 扩展中的新"显示追踪查看器"按钮提供:

    Playwright UI Mode

  • UI 模式和追踪查看器现在会标记通过 page.route()browserContext.route() 处理的网络请求,以及通过 API 测试 发起的请求:

    Trace Viewer

  • 为以下方法新增了 maskColor 选项:page.screenshot()locator.screenshot()expect(page).toHaveScreenshot()expect(locator).toHaveScreenshot(),用于更改默认的遮罩颜色:

    await page.goto('https://playwright.dev');
    await expect(page).toHaveScreenshot({
    mask: [page.locator('img')],
    maskColor: '#00FF00', // 绿色
    });
  • 新增 uninstall CLI 命令用于卸载浏览器二进制文件:

    $ npx playwright uninstall # 移除当前安装的浏览器
    $ npx playwright uninstall --all # 移除所有曾经安装的 Playwright 浏览器
  • UI 模式和追踪查看器现在都可以在浏览器标签页中打开:

    $ npx playwright test --ui-port 0 # 在随机端口上以标签页形式打开 UI 模式
    $ npx playwright show-trace --port 0 # 在随机端口上以标签页形式打开追踪查看器

⚠️ 重大变更

  • playwright-core 二进制文件名称已从 playwright 更改为 playwright-core。如果您使用 playwright-core 命令行工具,请确保更新名称:

    $ npx playwright-core install # 使用 playwright-core 时安装浏览器的新方式

    此项变更 不会 影响 @playwright/testplaywright 包的用户。

浏览器版本

  • Chromium 115.0.5790.13
  • Mozilla Firefox 113.0
  • WebKit 16.4

此版本还针对以下稳定版渠道进行了测试:

  • Google Chrome 114
  • Microsoft Edge 114

版本 1.34

亮点功能

  • UI 模式现在支持显示步骤、fixtures 和附件:UI Mode attachments

  • 新增属性 testProject.teardown 用于指定在当前项目及其所有依赖项目完成后需要运行的项目。Teardown 可用于清理该项目获取的任何资源。

    常见模式是设置一个 setup 依赖项及其对应的 teardown

    playwright.config.ts
    import { 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 用于创建预配置的 expect 实例,可自定义默认参数如 timeoutsoft

    const slowExpect = expect.configure({ timeout: 10000 });
    await slowExpect(locator).toHaveText('Submit');

    // 始终执行软断言
    const softExpect = expect.configure({ soft: true });
  • testConfig.webServer 新增选项 stderrstdout 用于配置输出处理:

    playwright.config.ts
    import { defineConfig } from '@playwright/test';

    export default defineConfig({
    // 在测试开始前运行本地开发服务器
    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() 可精确定位事件来源。

⚠️ 重大变更

  • 如果同时安装了 playwright@playwright/testnpx playwright test 将不再工作。没有必要同时安装这两个包,因为你可以直接从 @playwright/test 导入浏览器自动化 API:

    automation.ts
    import { chromium, firefox, webkit } from '@playwright/test';
    /* ... */
  • 不再支持 Node.js 14,因为它已于 2023 年 4 月 30 日终止支持

浏览器版本

  • Chromium 114.0.5735.26
  • Mozilla Firefox 113.0
  • WebKit 16.4

此版本还针对以下稳定渠道进行了测试:

  • Google Chrome 113
  • Microsoft Edge 113

版本 1.33

定位器更新

  • 使用 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() 中使用新选项 hasNothasNotText 来查找不匹配特定条件的元素。

    const rowLocator = page.locator('tr');
    await rowLocator
    .filter({ hasNotText: 'text in column 1' })
    .filter({ hasNot: page.getByRole('button', { name: 'column 2 button' }) })
    .screenshot();
  • 使用新的 web-first 断言 expect(locator).toBeAttached() 来确保元素存在于页面的 DOM 中。不要与 expect(locator).toBeVisible() 混淆,后者确保元素既存在于 DOM 中又可见。

新增 API

⚠️ 重大变更

  • mcr.microsoft.com/playwright:v1.33.0 现在提供基于 Ubuntu Jammy 的 Playwright 镜像。如需使用基于 focal 的镜像,请改用 mcr.microsoft.com/playwright:v1.33.0-focal

浏览器版本

  • Chromium 113.0.5672.53
  • Mozilla Firefox 112.0
  • WebKit 16.4

此版本也已针对以下稳定渠道进行测试:

  • Google Chrome 112
  • Microsoft Edge 112

版本 1.32

推出 UI 模式(预览版)

全新的 UI 模式 可让您探索、运行和调试测试,并内置了监视模式。

Playwright UI 模式

使用新标志 --ui 启用:

npx playwright test --ui

新增 API

⚠️ 组件测试的重大变更

注意:仅影响组件测试,不影响端到端测试。

  • @playwright/experimental-ct-react 现在仅支持 React 18
  • 如果您正在使用 React 16 或 17 运行组件测试,请将 @playwright/experimental-ct-react 替换为 @playwright/experimental-ct-react17

浏览器版本

  • Chromium 112.0.5615.29
  • Mozilla Firefox 111.0
  • WebKit 16.4

此版本还针对以下稳定渠道进行了测试:

  • Google Chrome 111
  • Microsoft Edge 111

版本 1.31

新增 API

  • 新增属性 testProject.dependencies 用于配置项目间的依赖关系。

    使用依赖关系可以让全局配置生成追踪记录和其他产物,在测试报告中查看配置步骤等。

    playwright.config.ts
    import { 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() 确保定位器指向的元素与视口相交,基于 intersection observer API 实现。

    const button = page.getByRole('button');

    // 确保元素至少部分与视口相交
    await expect(button).toBeInViewport();

    // 确保元素完全位于视口之外
    await expect(button).not.toBeInViewport();

    // 确保至少一半元素与视口相交
    await expect(button).toBeInViewport({ ratio: 0.5 });

杂项更新

  • 现在可以在单独窗口中打开追踪查看器中的 DOM 快照
  • 新增 defineConfig 方法用于 playwright.config 配置
  • route.fetch() 方法新增 maxRedirects 选项
  • Playwright 现在支持 Debian 11 arm64 架构
  • 官方 docker 镜像 现在包含 Node 18 而非 Node 16

⚠️ 组件测试的重大变更

注意:仅影响组件测试,不影响端到端测试。

组件测试playwright-ct.config 配置文件现在需要调用 defineConfig

// 变更前

import { type PlaywrightTestConfig, devices } from '@playwright/experimental-ct-react';
const config: PlaywrightTestConfig = {
// ... 配置内容 ...
};
export default config;

config 变量定义替换为 defineConfig 调用:

// 变更后

import { defineConfig, devices } from '@playwright/experimental-ct-react';
export default defineConfig({
// ... 配置内容 ...
});

浏览器版本

  • Chromium 111.0.5563.19
  • Mozilla Firefox 109.0
  • WebKit 16.4

此版本也已针对以下稳定渠道进行测试:

  • Google Chrome 110
  • Microsoft Edge 110

版本 1.30

浏览器版本

  • Chromium 110.0.5481.38
  • Mozilla Firefox 108.0.2
  • WebKit 16.4

此版本也已针对以下稳定渠道进行测试:

  • Google Chrome 109
  • Microsoft Edge 109

版本 1.29

新 API

  • 新增方法 route.fetch() 以及 route.fulfill() 的新选项 json

    await page.route('**/api/settings', async route => {
    // 获取原始设置
    const response = await route.fetch();

    // 强制将主题设置为预定义值
    const json = await response.json();
    json.theme = 'Solorized';

    // 返回修改后的数据
    await route.fulfill({ json });
    });
  • 新增方法 locator.all() 用于遍历所有匹配元素:

    // 勾选所有复选框!
    const checkboxes = page.getByRole('checkbox');
    for (const checkbox of await checkboxes.all())
    await checkbox.check();
  • locator.selectOption() 现在支持通过值或标签匹配:

    <select multiple>
    <option value="red">红色</option>
    <option value="green">绿色</option>
    <option value="blue">蓝色</option>
    </select>
    await element.selectOption('红色');
  • 重试代码块直到所有断言通过:

    await expect(async () => {
    const response = await page.request.get('https://api.example.com');
    await expect(response).toBeOK();
    }).toPass();

    更多信息请参阅 我们的文档

  • 测试失败时自动捕获 完整页面截图

    playwright.config.ts
    import { defineConfig } from '@playwright/test';
    export default defineConfig({
    use: {
    screenshot: {
    mode: 'only-on-failure',
    fullPage: true,
    }
    }
    });

杂项更新

浏览器版本

  • Chromium 109.0.5414.46
  • Mozilla Firefox 107.0
  • WebKit 16.4

此版本还在以下稳定渠道进行了测试:

  • Google Chrome 108
  • Microsoft Edge 108

版本 1.28

Playwright 工具

  • VSCode 光标处录制。您可以运行测试,将光标定位在测试末尾并继续生成测试。

新版 VSCode 扩展

  • VSCode 实时定位器。在 VSCode 中悬停并编辑定位器,可在打开的浏览器中高亮显示对应元素。
  • CodeGen 实时定位器。使用"探索"工具为页面上的任何元素生成定位器。

定位器探索器

  • Codegen 和 Trace Viewer 深色主题。自动从操作系统设置中获取。

深色主题

测试运行器

新增 API

浏览器版本

  • Chromium 108.0.5359.29
  • Mozilla Firefox 106.0
  • WebKit 16.4

此版本还针对以下稳定版渠道进行了测试:

  • Google Chrome 107
  • Microsoft Edge 107

版本 1.27

定位器

使用这些新 API 编写定位器是一种享受:

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();

所有这些方法同样适用于 LocatorFrameLocatorFrame 类。

其他亮点

  • playwright.config.ts 中的 workers 选项现在支持百分比字符串来使用部分可用 CPU。也可以通过命令行传递:

    npx playwright test --workers=20%
  • HTML 报告器新增 hostport 选项:

    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 更新。

行为变更

  • expect(locator).toHaveAttribute() 使用空值作为参数时,不再匹配缺失的属性。例如,以下代码片段将在 button 没有 disabled 属性时通过断言:

    await expect(page.getByRole('button')).toHaveAttribute('disabled', '');
  • 命令行选项 --grep--grep-invert 之前错误地忽略了配置文件中指定的 grepgrepInvert 选项。现在这些选项会共同生效。

浏览器版本

  • Chromium 107.0.5304.18
  • Mozilla Firefox 105.0.1
  • WebKit 16.0

此版本还在以下稳定渠道进行了测试:

  • Google Chrome 106
  • Microsoft Edge 106

版本 1.26

断言功能

其他亮点

  • apiRequestContext.get() 等接口新增 maxRedirects 选项,用于限制重定向次数
  • 新增命令行参数 --pass-with-no-tests,允许在未找到测试文件时测试套件仍能通过
  • 新增命令行参数 --ignore-snapshots,用于跳过快照断言,如 expect(value).toMatchSnapshot()expect(page).toHaveScreenshot()

行为变更

许多 Playwright API 已经支持 waitUntil: 'domcontentloaded' 选项。例如:

await page.goto('https://playwright.dev', {
waitUntil: 'domcontentloaded',
});

在 1.26 版本之前,这会等待所有 iframe 触发 DOMContentLoaded 事件。

为了与 Web 规范保持一致,'domcontentloaded' 值现在仅等待目标框架触发 'DOMContentLoaded' 事件。如需等待所有 iframe,请使用 waitUntil: 'load'

浏览器版本

  • Chromium 106.0.5249.30
  • Mozilla Firefox 104.0
  • WebKit 16.0

此版本还针对以下稳定版渠道进行了测试:

  • Google Chrome 105
  • Microsoft Edge 105

版本 1.25

VSCode 扩展

  • 实时观看测试运行并保持开发者工具打开
  • 选择器拾取功能
  • 从当前页面状态录制新测试

vscode extension screenshot

测试运行器

  • test.step() 现在会返回步骤函数的执行结果:

    test('should work', async ({ page }) => {
    const pageTitle = await test.step('获取标题', async () => {
    await page.goto('https://playwright.dev');
    return await page.title();
    });
    console.log(pageTitle);
    });
  • 新增了 test.describe.fixme() 方法。

  • 新增了 'interrupted' 测试状态。

  • 支持通过 CLI 标志启用追踪:npx playwright test --trace=on

公告

  • 🎁 我们现在提供 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月起将不再支持。

浏览器版本

  • Chromium 105.0.5195.19
  • Mozilla Firefox 103.0
  • WebKit 16.0

此版本也已针对以下稳定渠道进行了测试:

  • Google Chrome 104
  • Microsoft Edge 104

版本 1.24

🌍 在 playwright.config.ts 中配置多个 Web 服务器

通过传递配置数组来启动多个 Web 服务器、数据库或其他进程:

playwright.config.ts
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

Playwright 现在支持在 x86_64 架构的 Debian 11 Bullseye 系统上运行 Chromium、Firefox 和 WebKit。如果您遇到任何问题,请告知我们!

Linux 支持情况如下:

| | Ubuntu 20.04 | Ubuntu 22.04 | Debian 11 | :--- | :---: | :---: | :---: | :---: | | Chromium | ✅ | ✅ | ✅ | | WebKit | ✅ | ✅ | ✅ | | Firefox | ✅ | ✅ | ✅ |

🕵️ 匿名测试套件

现在可以调用 test.describe() 来创建无标题的测试套件。这对于使用 test.use() 为一组测试提供共同选项非常有用。

test.describe(() => {
test.use({ colorScheme: 'dark' });

test('one', async ({ page }) => {
// ...
});

test('two', async ({ page }) => {
// ...
});
});

🧩 组件测试更新

Playwright 1.24 版本的组件测试引入了 beforeMountafterMount 钩子函数。使用这些钩子可以为测试配置你的应用。

例如,这可以用于在 Vue.js 中设置应用路由:

src/component.spec.ts
import { test } from '@playwright/experimental-ct-vue';
import { Component } from './mycomponent';

test('should work', async ({ mount }) => {
const component = await mount(Component, {
hooksConfig: {
/* 任何需要配置应用的参数 */
}
});
});
playwright/index.ts
import { router } from '../router';
import { beforeMount } from '@playwright/experimental-ct-vue/hooks';

beforeMount(async ({ app, hooksConfig }) => {
app.use(router);
});

在 Next.js 中的类似配置如下所示:

src/component.spec.jsx
import { test } from '@playwright/experimental-ct-react';
import { Component } from './mycomponent';

test('should work', async ({ mount }) => {
const component = await mount(<Component></Component>, {
// 将模拟值从测试传递到 `beforeMount`
hooksConfig: {
router: {
query: { page: 1, per_page: 10 },
asPath: '/posts'
}
}
});
});
playwright/index.js
import router from 'next/router';
import { beforeMount } from '@playwright/experimental-ct-react/hooks';

beforeMount(async ({ hooksConfig }) => {
// 在挂载前,重新定义 useRouter 以返回测试中的模拟值
router.useRouter = () => hooksConfig.router;
});

版本 1.23

网络回放

现在您可以将网络流量记录到 HAR 文件中,并在测试中重复使用这些流量。

将网络记录到 HAR 文件:

npx playwright open --save-har=github.har.zip https://github.com/microsoft

或者,您也可以通过编程方式记录 HAR:

const context = await browser.newContext({
recordHar: { path: 'github.har.zip' }
});
// ... 执行操作 ...
await context.close();

使用新方法 page.routeFromHAR()browserContext.routeFromHAR()HAR 文件提供匹配的响应:

await context.routeFromHAR('github.har.zip');

更多信息请参阅 我们的文档

高级路由

现在您可以使用 route.fallback() 将路由推迟给其他处理程序。

考虑以下示例:

// 从所有请求中移除一个标头
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('应该正常工作', async ({ page }) => {
await page.route('**/*', async route => {
if (route.request().resourceType() === 'image')
await route.abort();
else
await route.fallback();
});
});

请注意,新方法 page.routeFromHAR()browserContext.routeFromHAR() 也会参与路由,并可以被推迟处理。

Web-First 断言更新

组件测试更新

了解更多关于 使用 Playwright 进行组件测试 的信息。

其他更新

  • 如果存在阻碍测试的 Service Worker,现在可以通过新的上下文选项 serviceWorkers 轻松禁用它:

    playwright.config.ts
    export default {
    use: {
    serviceWorkers: 'block',
    }
    };
  • recordHar 上下文选项使用 .zip 路径会自动压缩生成的 HAR 文件:

    const context = await browser.newContext({
    recordHar: {
    path: 'github.har.zip',
    }
    });
  • 如需手动编辑 HAR 文件,建议使用 "minimal" 记录模式,该模式仅记录回放必需的信息:

    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

⚠️ 破坏性变更 ⚠️

当向指定 URL 的请求返回以下任一 HTTP 状态码时,WebServer 现在会被视为"就绪":

  • 200-299
  • 300-399 (新增)
  • 400, 401, 402, 403 (新增)

版本 1.22

亮点功能

  • 组件测试(预览版)

    Playwright Test 现在可以测试你的 ReactVue.jsSvelte 组件。你可以在真实浏览器中运行组件的同时,使用 Playwright Test 的所有功能(如并行化、模拟和调试)。

    这是一个典型的组件测试示例:

    App.spec.tsx
    import { test, expect } from '@playwright/experimental-ct-react';
    import App from './App';

    // 让我们在深色模式下测试组件!
    test.use({ colorScheme: 'dark' });

    test('should render', async ({ mount }) => {
    const component = await mount(<App></App>);

    // 和任何 Playwright 测试一样,断言定位器文本
    await expect(component).toContainText('React');
    // 或者进行截图 🚀
    await expect(component).toHaveScreenshot();
    // 或者使用任何 Playwright 方法
    await component.click();
    });

    更多内容请阅读 我们的文档

  • 角色选择器,允许通过 ARIA 角色ARIA 属性可访问名称 来选择元素。

    // 点击可访问名称为"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();
  • 新的面向 Web 的断言 expect(page).toHaveScreenshot()expect(locator).toHaveScreenshot(),它们会等待截图稳定,从而提高测试可靠性。

    新断言具有特定于截图的默认设置,例如:

    • 禁用动画
    • 使用 CSS 缩放选项
    await page.goto('https://playwright.dev');
    await expect(page).toHaveScreenshot();

    新的 expect(page).toHaveScreenshot() 会将截图保存在与 expect(value).toMatchSnapshot() 相同的位置。

版本 1.21

亮点功能

  • 新增角色选择器,支持通过 ARIA 角色ARIA 属性可访问名称 选择元素。

    // 点击可访问名称为"log in"的按钮
    await page.locator('role=button[name="log in"]').click();

    更多信息请参阅 我们的文档

  • page.screenshot() 新增 scale 选项,可生成更小尺寸的截图。

  • page.screenshot() 新增 caret 选项用于控制文本光标的显示,默认为 "hide"

  • 新增 expect.poll 方法用于等待任意条件满足:

    // 轮询方法直到返回预期结果
    await expect.poll(async () => {
    const response = await page.request.get('https://api.example.com');
    return response.status();
    }).toBe(200);

    expect.poll 支持大多数同步匹配器,如 .toBe().toContain() 等。更多信息请参阅 我们的文档

行为变更

  • 运行 TypeScript 测试时的 ESM 支持现已默认启用,不再需要 PLAYWRIGHT_EXPERIMENTAL_TS_ESM 环境变量。
  • mcr.microsoft.com/playwright Docker 镜像不再包含 Python。如需预装 Python 的 Playwright-ready Docker 镜像,请使用 mcr.microsoft.com/playwright/python
  • Playwright 现在支持通过 locator.setInputFiles() API 上传大文件(数百 MB)。

浏览器版本

  • Chromium 101.0.4951.26
  • Mozilla Firefox 98.0.2
  • WebKit 15.4

此版本还针对以下稳定渠道进行了测试:

  • Google Chrome 100
  • Microsoft Edge 100

版本 1.20

亮点功能

  • 为以下方法新增选项 page.screenshot()locator.screenshot()elementHandle.screenshot():

    • 选项 animations: "disabled" 可将所有 CSS 动画和过渡重置到一致状态
    • 选项 mask: Locator[] 可遮盖指定元素,用粉色 #FF00FF 方框覆盖它们
  • expect().toMatchSnapshot() 现在支持匿名快照:当快照名称缺失时,Playwright Test 会自动生成一个:

    expect('Web is Awesome <3').toMatchSnapshot();
  • 新增 maxDiffPixelsmaxDiffPixelRatio 选项,用于通过 expect().toMatchSnapshot() 进行精细的截图比较:

    expect(await page.screenshot()).toMatchSnapshot({
    maxDiffPixels: 27, // 允许最多27个不同像素
    });

    最方便的做法是在 testConfig.expect 中一次性指定 maxDiffPixelsmaxDiffPixelRatio

  • Playwright Test 现在新增了 testConfig.fullyParallel 模式。默认情况下,Playwright Test 在文件之间并行执行。在全并行模式下,单个文件内的测试也会并行运行。你也可以使用 --fully-parallel 命令行标志。

    playwright.config.ts
    export default {
    fullyParallel: true,
    };
  • testProject.greptestProject.grepInvert 现在可按项目配置。例如,你现在可以使用 grep 配置冒烟测试项目:

    playwright.config.ts
    export default {
    projects: [
    {
    name: 'smoke tests',
    grep: /@smoke/,
    },
    ],
    };
  • Trace Viewer 现在会显示 API 测试请求

  • locator.highlight() 可以可视化高亮元素,便于调试。

重要公告

  • 我们现在提供了专门的 Python Docker 镜像 mcr.microsoft.com/playwright/python。如果您使用 Python,请切换到此镜像。这是最后一个在 JavaScript mcr.microsoft.com/playwright Docker 镜像中包含 Python 的版本。
  • v1.20 将是最后一个支持 macOS 10.15 Catalina 系统的 WebKit 更新版本。请升级 macOS 系统以继续使用最新最强的 WebKit!

浏览器版本

  • Chromium 101.0.4921.0
  • Mozilla Firefox 97.0.1
  • WebKit 15.4

此版本也已针对以下稳定版渠道进行测试:

  • Google Chrome 99
  • Microsoft Edge 99

版本 1.19

Playwright Test 更新

  • Playwright Test v1.19 现在支持软断言。失败的软断言

    不会终止测试执行,但会将测试标记为失败。

    // 进行一些检查,即使失败也不会停止测试...
    await expect.soft(page.locator('#status')).toHaveText('Success');
    await expect.soft(page.locator('#eta')).toHaveText('1 day');

    // ...然后继续测试以检查更多内容。
    await page.locator('#next-page').click();
    await expect.soft(page.locator('#title')).toHaveText('Make another order');

    更多信息请参阅我们的文档

  • 现在你可以为 expectexpect.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() 来并行运行它们。

其他更新

Playwright Test 全局设置中的潜在破坏性变更

此变更不太可能影响您,如果测试运行正常则无需采取任何措施。

我们注意到在极少数情况下,需要通过环境变量在全局设置中配置要执行的测试集。还发现一些应用会在全局拆卸阶段对报告输出进行后处理。如果您正在执行上述任一操作,请了解更多详情

浏览器版本

  • Chromium 100.0.4863.0
  • Mozilla Firefox 96.0.1
  • WebKit 15.4

此版本还针对以下稳定版渠道进行了测试:

  • Google Chrome 98
  • Microsoft Edge 98

版本 1.18

定位器改进

测试API改进

改进的TypeScript支持

  1. Playwright Test 现在支持 tsconfig.json 中的 baseUrlpaths,因此你可以使用别名
  2. 新增环境变量 PW_EXPERIMENTAL_TS_ESM,允许在TS代码中直接导入ESM模块而无需编译步骤。导入ESM模块时不要忘记添加.js后缀。按以下方式运行测试:
npm i --save-dev @playwright/test@1.18.0-rc1
PW_EXPERIMENTAL_TS_ESM=1 npx playwright test

Create Playwright

npm init playwright 命令现已正式可用:


# 从项目根目录运行
npm init playwright@latest

# 或创建新项目
npm init playwright@latest new-project

这将创建一个Playwright Test配置文件,可选添加示例、GitHub Action工作流和第一个测试文件example.spec.ts

新API及变更

重大变更:自定义配置选项

自定义配置选项是一种便捷的方式,可以为不同项目设置不同的参数值。更多信息请参阅本指南

在之前版本中,任何通过 test.extend() 引入的 fixture 都可以在 testProject.use 配置部分被覆盖。例如:

// 错误:此代码片段自 v1.18 起不再有效

// fixtures.js
const test = base.extend({
myParameter: 'default',
});

// playwright.config.js
module.exports = {
use: {
myParameter: 'value',
},
};

在配置文件中参数化 fixture 的正确方式是在定义 fixture 时指定 option: true。例如:

// 正确:此代码片段自 v1.18 起有效

// fixtures.js
const test = base.extend({
// 标记为 "option: true" 的 fixture 将从配置中获取值,
// 或回退到默认值
myParameter: ['default', { option: true }],
});

// playwright.config.js
module.exports = {
use: {
myParameter: 'value',
},
};

浏览器版本

  • Chromium 99.0.4812.0
  • Mozilla Firefox 95.0
  • WebKit 15.4

此版本还针对以下稳定渠道进行了测试:

  • Google Chrome 97
  • Microsoft Edge 97

版本 1.17

Frame Locators(框架定位器)

Playwright 1.17 引入了 frame locators - 用于定位页面中的 iframe。框架定位器封装了足够逻辑来获取 iframe 并在该 iframe 中定位元素。框架定位器默认是严格的,会等待 iframe 出现,并可用于 Web-First 断言。

图示

框架定位器可以通过 page.frameLocator()locator.frameLocator() 方法创建。

const locator = page.frameLocator('#my-iframe').locator('text=Submit');
await locator.click();

更多信息请参阅 我们的文档

Trace Viewer(追踪查看器)更新

Playwright Trace Viewer 现已 在线提供,访问 https://trace.playwright.dev!只需拖放您的 trace.zip 文件即可查看其内容。

注意:追踪文件不会上传到任何地方;trace.playwright.dev 是一个 渐进式 Web 应用,会在本地处理追踪文件。

  • Playwright Test 追踪现在默认包含源代码(可通过 tracing 选项关闭)
  • Trace Viewer 现在显示测试名称
  • 新增包含浏览器详情的追踪元数据标签页
  • 快照现在包含 URL 地址栏

图片

HTML 报告更新

  • HTML 报告现在支持动态筛选
  • 报告现在是 单个静态 HTML 文件,可通过电子邮件发送或作为 Slack 附件

图片

Ubuntu ARM64 支持及其他更新

  • Playwright 现已支持 Ubuntu 20.04 ARM64。现在可以在 Apple M1 和树莓派上的 Docker 容器中运行 Playwright 测试。

  • 现在可以使用 Playwright 在 Linux 上安装稳定版 Edge 浏览器:

    npx playwright install msedge

新增 API

版本 1.16

🎭 Playwright 测试

API 测试

Playwright 1.16 引入了全新的 API 测试 功能,允许你直接从 Node.js 向服务器发送请求!现在你可以:

  • 测试服务器 API
  • 在测试中访问网页应用前预先设置服务器端状态
  • 在浏览器中执行某些操作后验证服务器端后置条件

要代表 Playwright 的 Page 发起请求,请使用 全新的 page.request API

import { test, expect } from '@playwright/test';

test('context fetch', async ({ page }) => {
// 代表页面发起 GET 请求
const response = await page.request.get('http://example.com/foo.json');
// ...
});

要从 node.js 独立向 API 端点发起请求,请使用 全新的 request fixture

import { test, expect } from '@playwright/test';

test('context fetch', async ({ request }) => {
// 代表页面发起 GET 请求
const response = await request.get('http://example.com/foo.json');
// ...
});

更多信息请参阅我们的 API 测试指南

响应拦截

现在可以通过结合 API 测试请求拦截 来实现响应拦截功能。

例如,我们可以模糊处理页面上的所有图片:

import { test, expect } from '@playwright/test';
import jimp from 'jimp'; // 图像处理库

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.dev');
expect(response.status()).toBe(200);
});

了解更多关于 响应拦截 的信息。

全新 HTML 报告器

试用全新的 HTML 报告器,可通过 --reporter=html 或在 playwright.config.ts 文件中配置 reporter 项:

$ npx playwright test --reporter=html

HTML 报告器包含测试及其失败的所有信息,包括追踪记录和图像附件。

html 报告器

了解更多关于 我们的报告器 的信息。

🎭 Playwright 库

locator.waitFor

等待定位器解析为具有指定状态的单个元素。默认为 state: 'visible'

在处理列表时特别有用:

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() 的信息。

Docker 对 Arm64 的支持

Playwright Docker 镜像现已发布 Arm64 版本,可在 Apple Silicon 上使用。

了解更多关于 Docker 集成 的信息。

🎭 Playwright 追踪查看器

  • 追踪查看器内置网页优先断言
  • 使用 npx playwright show-trace 运行追踪查看器,并将追踪文件拖放至追踪查看器 PWA
  • API 测试已集成到追踪查看器
  • 操作目标的视觉归属更清晰

了解更多关于 追踪查看器 的信息。

浏览器版本

  • Chromium 97.0.4666.0
  • Mozilla Firefox 93.0
  • WebKit 15.4

此版本 Playwright 还针对以下稳定渠道进行了测试:

  • Google Chrome 94
  • Microsoft Edge 94

版本 1.15

🎭 Playwright 库

🖱️ 鼠标滚轮

通过使用 mouse.wheel(),您现在可以实现垂直或水平滚动。

📜 全新的 Headers API

之前无法获取响应中的多个头信息值,现在这一功能已经实现,并且新增了以下辅助函数:

🌈 强制色彩模拟

现在可以通过在 browser.newContext() 中传递参数或调用 page.emulateMedia() 来模拟 forced-colors CSS 媒体特性。

新增 API

🎭 Playwright 测试

🤝 test.parallel() 在同一个文件中并行运行测试

test.describe.parallel('group', () => {
test('并行运行测试1', async ({ page }) => {
});
test('并行运行测试2', async ({ page }) => {
});
});

默认情况下,单个文件中的测试是按顺序运行的。如果单个文件中有许多独立的测试,您现在可以使用 test.describe.parallel(title, callback) 来并行运行它们。

🛠 新增 --debug CLI 标志

通过使用 npx playwright test --debug 命令,它将启用 Playwright Inspector 来帮助您调试测试。

浏览器版本

  • Chromium 96.0.4641.0
  • Mozilla Firefox 92.0
  • WebKit 15.0

版本 1.14

🎭 Playwright 库

⚡️ 新增 "strict" 严格模式

选择器歧义是自动化测试中的常见问题。"strict" 严格模式 确保您的选择器指向单个元素,否则会抛出错误。

在操作调用中传入 strict: true 来启用此模式。

// 如果有多个按钮,这将会抛出错误!
await page.click('button', { strict: true });

📍 新增 Locators API

定位器(Locator)表示页面上元素的视图。它捕获了在任何给定时刻检索元素所需的逻辑。

LocatorElementHandle 的区别在于,后者指向特定元素,而 Locator 捕获了如何检索该元素的逻辑。

此外,定位器默认是 "strict" 严格模式

const locator = page.locator('button');
await locator.click();

了解更多信息,请参阅 文档

🧩 实验性 ReactVue 选择器引擎

React 和 Vue 选择器允许通过组件名称和/或属性值来选择元素。其语法与 属性选择器 非常相似,并支持所有属性选择器运算符。

await page.locator('_react=SubmitButton[enabled=true]').click();
await page.locator('_vue=submit-button[enabled=true]').click();

了解更多请参阅 React 选择器文档Vue 选择器文档

✨ 新增 nthvisible 选择器引擎

  • nth 选择器引擎等效于 :nth-match 伪类,但可以与其他选择器引擎组合使用。
  • visible 选择器引擎等效于 :visible 伪类,但可以与其他选择器引擎组合使用。
// 在所有按钮中选择第一个按钮
await button.click('button >> nth=0');
// 如果使用定位器,可以使用 first()、nth() 和 last()
await page.locator('button').first().click();

// 点击可见的按钮
await button.click('button >> visible=true');

🎭 Playwright 测试

✅ 网页优先断言

expect 现在支持大量新的网页优先断言。

请看以下示例:

await expect(page.locator('.status')).toHaveText('Submitted');

Playwright Test 会不断重新测试带有 .status 选择器的节点,直到获取到的节点包含 "Submitted" 文本为止。它会持续重新获取节点并检查,直到满足条件或达到超时时间。你可以通过传递超时参数,或者在测试配置中通过 testProject.expect 值一次性配置。

默认情况下,断言没有设置超时时间,因此会一直等待,直到整个测试超时为止。

所有新断言的列表:

⛓ 使用 describe.serial 的串行模式

声明一组应该始终以串行方式运行的测试。如果其中一个测试失败,所有后续测试将被跳过。组中的所有测试会一起重试。

test.describe.serial('group', () => {
test('runs first', async ({ page }) => { /* ... */ });
test('runs second', async ({ page }) => { /* ... */ });
});

了解更多请参阅 文档

🐾 使用 test.step 的步骤 API

使用 test.step() API 将长测试拆分为多个步骤:

import { test, expect } from '@playwright/test';

test('test', async ({ page }) => {
await test.step('登录', async () => {
// ...
});
await test.step('新闻动态', async () => {
// ...
});
});

步骤信息会在报告器 API 中展示。

🌎 在运行测试前启动 web 服务器

要在测试期间启动服务器,请在配置文件中使用 webServer 选项。服务器会在运行测试前等待指定 URL 可用,该 URL 会在创建上下文时作为 baseURL 传递给 Playwright。

playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
webServer: {
command: 'npm run start', // 启动命令
url: 'http://127.0.0.1:3000', // 等待的 URL
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
},
});

了解更多请参阅 文档

浏览器版本

  • Chromium 94.0.4595.0
  • Mozilla Firefox 91.0
  • WebKit 15.0

版本 1.13

Playwright Test

Playwright

  • 🖖 通过 page.dragAndDrop() API 实现编程式拖放支持
  • 🔎 增强的 HAR 功能,现在包含请求和响应的 body 大小。可通过 browser.newContext() 中的 recordHar 选项使用。

工具

  • Playwright Trace Viewer 现在可以显示参数、返回值以及 console.log() 调用。
  • Playwright Inspector 能够生成 Playwright Test 测试用例。

新增与重构的指南

浏览器版本

  • Chromium 93.0.4576.0
  • Mozilla Firefox 90.0
  • WebKit 14.2

新增 Playwright API

版本 1.12

⚡️ Playwright Test 简介

Playwright Test 是 Playwright 团队全新开发的测试运行器,专为满足端到端测试需求而设计:

  • 支持所有浏览器运行测试
  • 可并行执行测试用例
  • 开箱即用的上下文隔离和合理默认配置
  • 失败时自动捕获视频、截图等诊断信息
  • 可将页面对象模型(POM)集成为可扩展的fixture

安装方法:

npm i -D @playwright/test

简单测试示例 tests/foo.spec.ts

import { test, expect } from '@playwright/test';

test('basic test', async ({ page }) => {
await page.goto('https://playwright.dev/');
const name = await page.innerText('.navbar__title');
expect(name).toBe('Playwright');
});

运行命令:

npx playwright test

👉 更多内容请参阅 Playwright Test 文档

🧟‍♂️ Playwright Trace Viewer 介绍

Playwright Trace Viewer 是一个全新的 GUI 工具,用于在脚本运行后探索已录制的 Playwright 追踪记录。Playwright 追踪记录可让您检查:

  • 每次 Playwright 操作前后的页面 DOM 状态
  • 每次 Playwright 操作前后的页面渲染情况
  • 脚本执行期间的浏览器网络活动

追踪记录通过新的 browserContext.tracing API 进行录制:

const browser = await chromium.launch();
const context = await browser.newContext();

// 在创建/导航页面之前开始追踪
await context.tracing.start({ screenshots: true, snapshots: true });

const page = await context.newPage();
await page.goto('https://playwright.dev');

// 停止追踪并导出为 zip 存档
await context.tracing.stop({ path: 'trace.zip' });

之后可以使用 Playwright CLI 查看追踪记录:

npx playwright show-trace trace.zip

这将打开以下 GUI 界面:

image

👉 更多详情请参阅 追踪查看器文档

浏览器版本

  • Chromium 93.0.4530.0
  • Mozilla Firefox 89.0
  • WebKit 14.2

此版本的 Playwright 还针对以下稳定版渠道进行了测试:

  • Google Chrome 91
  • Microsoft Edge 91

新增 API

版本 1.11

🎥 新视频: Playwright:面向现代 Web 的新测试自动化框架 (幻灯片)

  • 我们探讨了 Playwright 框架
  • 展示了幕后的工程技术工作
  • 现场演示了新功能 ✨
  • 特别感谢 applitools 主办此次活动并邀请我们!

浏览器版本

  • Chromium 92.0.4498.0
  • Mozilla Firefox 89.0b6
  • WebKit 14.2

新增 API

版本 1.10

捆绑浏览器版本

  • Chromium 90.0.4430.0
  • Mozilla Firefox 87.0b10
  • WebKit 14.2

此版本 Playwright 还针对以下稳定版浏览器进行了测试:

  • Google Chrome 89
  • Microsoft Edge 89

新增 API

版本 1.9

  • Playwright Inspector 是一个全新的 GUI 工具,用于编写和调试测试。
    • 支持逐行调试 Playwright 脚本,具有播放、暂停和单步执行功能。
    • 通过记录用户操作来编写新脚本。
    • 通过悬停在元素上生成元素选择器
    • 设置 PWDEBUG=1 环境变量来启动 Inspector
  • 在 headed 模式下使用 page.pause() 暂停脚本执行。暂停页面时会启动 Playwright Inspector 进行调试。
  • 新增 has-text 伪类用于 CSS 选择器。:has-text("example") 可以匹配任何包含 "example" 的元素,包括子元素或后代元素。查看更多示例
  • 页面对话框现在会自动关闭,除非配置了 dialog 事件监听器。了解更多关于对话框处理
  • Playwright for Python 现已稳定发布,提供符合 Python 习惯的蛇形命名 API 和预构建的 Docker 镜像用于 CI/CD 测试。

浏览器版本

  • Chromium 90.0.4421.0
  • Mozilla Firefox 86.0b10
  • WebKit 14.1

新增 API

版本 1.8

新增 API

浏览器版本

  • Chromium 90.0.4392.0
  • Mozilla Firefox 85.0b5
  • WebKit 14.1

版本 1.7

  • 全新 Java SDKPlaywright for Java 现已与 JavaScriptPython.NET 绑定 保持功能同步。
  • 浏览器存储 API:新增便捷 API 用于保存和加载浏览器存储状态(cookies、本地存储),简化涉及身份验证的自动化场景。
  • 全新 CSS 选择器:我们听取了您对更灵活选择器的反馈,并重构了选择器实现。Playwright 1.7 引入了新的 CSS 扩展,更多功能即将推出。
  • 新版网站:文档网站 playwright.dev 已更新,现基于 Docusaurus 构建。
  • Apple Silicon 支持:WebKit 和 Chromium 的 Playwright 浏览器二进制文件现已支持 Apple Silicon 架构。

新增 API

浏览器版本

  • Chromium 89.0.4344.0
  • Mozilla Firefox 84.0b9
  • WebKit 14.1