跳到主要内容

发布说明

版本 1.50

测试运行器

  • 新选项 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(),允许在单独的 YAML 文件中存储 aria 快照。

  • 添加了方法 expect(locator).toHaveAccessibleErrorMessage(),以断言 Locator 指向具有给定 aria errormessage 的元素。

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

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

    npx playwright test --update-snapshots=changed --update-source-method=3way
  • 选项 testConfig.webServer 为指定默认 SIGKILL 之外的进程终止信号添加了 gracefulShutdown 字段。

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

UI 更新

  • 更新了默认 HTML 报告器,以改进附件的显示。
  • 用于选择元素以生成 aria 快照的新按钮。
  • 其他详细信息(例如按下的键)现在与跟踪中的操作 API 调用一起显示。
  • canvas 内容在跟踪中的显示容易出错。现在默认禁用显示,可以通过 Display canvas content UI 设置启用。
  • CallNetwork 面板现在显示其他时间信息。

重大变更

浏览器版本

  • 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.net.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"
`);

您可以使用 测试生成器 生成此断言,并使用 --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 连接。以下是一个简单的示例,通过使用 "response" 响应 "request" 来模拟 WebSocket 通信。

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

有关更多详细信息,请参阅 WebSocketRoute

UI 更新

  • HTML 报告中用于注释和测试位置的新“复制”按钮。
  • 路由方法调用(如 route.fulfill())不再显示在报告和跟踪查看器中。您可以在网络选项卡中查看哪些网络请求被路由。
  • 网络选项卡中请求的新“复制为 cURL”和“复制为 fetch”按钮。

其他

  • 选项 form 和类似的选项现在接受 FormData
  • 新方法 page.requestGC() 可能有助于检测内存泄漏。
  • 新选项 location 用于传递自定义步骤位置。
  • APIRequestContext 发出的请求现在在 HAR 中记录详细的计时和安全信息。

浏览器版本

  • Chromium 130.0.6723.19
  • Mozilla Firefox 130.0
  • WebKit 18.0

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

  • Google Chrome 129
  • Microsoft Edge 129

版本 1.47

网络选项卡改进

UI 模式和跟踪查看器中的网络选项卡进行了一些不错的改进

  • 按资产类型和 URL 过滤
  • 更好地显示查询字符串参数
  • 字体资产预览

Network tab now has filters

--tsconfig CLI 选项

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

# Pass a specific tsconfig
npx playwright test --tsconfig tsconfig.test.json

APIRequestContext 现在接受 URLSearchParamsstring 作为查询参数

您现在可以将 URLSearchParamsstring 作为查询参数传递给 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'
}
);
// ...
});

其他

  • mcr.microsoft.com/playwright:v1.47.0 现在提供基于 Ubuntu 24.04 Noble 的 Playwright 镜像。要使用基于 22.04 jammy 的镜像,请改用 mcr.microsoft.com/playwright:v1.47.0-jammy
  • 新选项 behaviorbehaviorbehavior 用于等待正在进行的侦听器完成。
  • TLS 客户端证书现在可以通过传递 clientCertificates.certclientCertificates.key 作为缓冲区而不是文件路径从内存中传递。
  • 具有 text/html 内容类型的附件现在可以在 HTML 报告中的新选项卡中打开。这对于在 Playwright 测试报告中包含第三方报告或其他 HTML 内容并将其分发给您的团队非常有用。
  • noWaitAfter 选项在 locator.selectOption() 中已弃用。
  • 我们已经看到有关 WebGL 在 GitHub Actions macos-13 上 Webkit 行为异常的报告。我们建议将 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 选项

新的 CLI 选项 --only-changed 将仅运行自上次 git 提交或特定 git “ref”以来已更改的测试文件。这还将运行导入任何已更改文件的所有测试文件。

# 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 fixture

此版本引入了一个实验性的 router fixture,用于在组件测试中拦截和处理网络请求。有两种方法可以使用 router fixture

  • 调用 router.route(url, handler),其行为类似于 page.route()
  • 调用 router.use(handlers) 并将 MSW 库 请求处理程序传递给它。

以下是在测试中重用现有 MSW 处理程序的示例。

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
// ...
});

此 fixture 仅在 组件测试 中可用。

UI 模式 / Trace 查看器更新

  • 测试注释现在显示在 UI 模式中。
  • 文本附件的内容现在以内联方式呈现在附件窗格中。
  • 用于显示/隐藏路由操作(如 route.continue())的新设置。
  • 请求方法和状态显示在网络详细信息选项卡中。
  • 用于将源文件位置复制到剪贴板的新按钮。
  • 元数据窗格现在显示 baseURL

其他

  • apiRequestContext.fetch() 中的新 maxRetries 选项,用于在 ECONNRESET 网络错误时重试。
  • 用于 box a fixture 的新选项,以最大限度地减少 fixture 在测试报告和错误消息中的暴露。
  • 用于提供 自定义 fixture 标题 以在测试报告和错误消息中使用的新选项。

浏览器版本

  • Chromium 128.0.6613.18
  • Mozilla Firefox 128.0
  • WebKit 18.0

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

  • Google Chrome 127
  • Microsoft Edge 127

版本 1.45

时钟

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

  • 使用预定义时间进行测试;
  • 保持一致的时间和计时器;
  • 监控不活动状态;
  • 手动滴答计时。
// Initialize clock and let the page load naturally.
await page.clock.install({ time: new Date('2024-02-02T08:00:00') });
await page.goto('https://127.0.0.1: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');

有关更多详细信息,请参阅 时钟指南

测试运行器

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

  • 新的环境变量 PLAYWRIGHT_FORCE_TTY 控制内置 listlinedot 报告器是否假定为实时终端。例如,当您的 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.respectGitIgnoretestProject.respectGitIgnore 控制在搜索测试时是否排除与 .gitignore 模式匹配的文件。

  • 新属性 timeout 现在可用于自定义 expect 匹配器。此属性考虑了 playwright.config.tsexpect.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 ...
    },
    });

其他

  • 方法 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,允许在特定地址而不是未指定的 0.0.0.0 上接受 websocket 连接。

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

  • v1.45 是最后一个接收 macOS 12 Monterey WebKit 更新的版本。请更新 macOS 以继续使用最新的 WebKit。

浏览器版本

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

定位器处理程序

  • 在执行使用 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);

其他选项

  • multipart 选项在 apiRequestContext.fetch() 中现在接受 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 中的 expect.toPass.intervals 选项全局配置,或在 testProject.expect 中按项目配置。

  • 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

    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)

浏览器版本

  • Chromium 125.0.6422.14
  • Mozilla Firefox 125.0.1
  • WebKit 17.4

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

  • Google Chrome 124
  • Microsoft Edge 124

版本 1.43

新 API

  • 方法 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' });
  • retain-on-first-failure 模式用于 testOptions.trace。在此模式下,为每个测试的第一次运行记录跟踪,但不为重试记录。当测试运行失败时,将保留跟踪文件,否则将其删除。

    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 Mode

  • 在测试列表中查看标签。
  • 通过键入 @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 对话框出现时如何关闭它
// 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();
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' }));
  • 新语法 用于向测试添加标签(测试标题中的 @-tokens 仍然受支持)
test('test customer login', {
tag: ['@fast', '@login'],
}, async ({ page }) => {
// ...
});

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

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.net.cn/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 Test Generator

生成断言的新工具

这是一个带有断言的生成测试示例

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

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

其他更改

浏览器版本

  • 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 }) {
// ... see documentation for how to write matchers.
},
});

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

请参阅完整示例的文档

合并测试 fixtures

您现在可以从多个文件或模块合并测试 fixtures

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 }) => {
// use database and a11y fixtures.
});

合并自定义 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('passes', async ({ page, database }) => {
await expect(database).toHaveDatabaseUser('admin');
await expect(page).toPassA11yAudit();
});

隐藏实现细节:框式测试步骤

您可以将 test.step() 标记为 “boxed”,以便其中的错误指向步骤调用站点。

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() 文档以获取完整示例。

新 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 Mode

  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 现在在 x86_64 和 arm64 上都支持 Debian 12 Bookworm,用于 Chromium、Firefox 和 WebKit。 如果您遇到任何问题,请告诉我们!

Linux 支持看起来像这样

Ubuntu 20.04Ubuntu 22.04Debian 11Debian 12
Chromium
WebKit
Firefox

UI 模式更新

  • UI 模式现在尊重项目依赖项。 您可以通过在项目列表中选中/取消选中它们来控制要尊重的依赖项。
  • 来自测试的控制台日志现在显示在“控制台”选项卡中。

浏览器版本

  • 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 扩展中的新 “显示 trace viewer” 按钮使用

    Playwright UI Mode

  • UI 模式和 trace viewer 标记使用 page.route()browserContext.route() 处理程序处理的网络请求,以及通过 API 测试 发出的请求

    Trace Viewer

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

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

    $ npx playwright uninstall # remove browsers installed by this installation
    $ npx playwright uninstall --all # remove all ever-install Playwright browsers
  • UI 模式和 trace viewer 现在都可以在浏览器选项卡中打开

    $ 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

⚠️ 重大更改

  • playwright-core 二进制文件已从 playwright 重命名为 playwright-core。 因此,如果您使用 playwright-core CLI,请确保更新名称

    $ npx playwright-core install # the new way to install browsers when using 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 对于清理此项目获取的任何资源很有用。

    常见的模式将是具有相应 teardownsetup 依赖项

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

    // Always do soft assertions.
    const softExpect = expect.configure({ soft: true });
  • testConfig.webServer 中的新选项 stderrstdout 用于配置输出处理

    playwright.config.ts
    import { 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() 用于创建与两个 locator 都匹配的 locator。

    const button = page.getByRole('button').and(page.getByTitle('Subscribe'));
  • 新事件 browserContext.on('console')browserContext.on('dialog') 用于订阅来自给定浏览器上下文的任何页面的任何对话框和控制台消息。 使用新方法 consoleMessage.page()dialog.page() 来精确定位事件源。

⚠️ 重大更改

  • 如果您同时安装了 playwright@playwright/test,则 npx 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

Locators 更新

  • 使用 locator.or() 创建一个与两个 locator 之一匹配的 locator。 考虑这样一种情况:您想单击 “新邮件” 按钮,但有时会出现安全设置对话框。 在这种情况下,您可以等待 “新邮件” 按钮或对话框,并采取相应的措施

    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() 混淆,后者确保元素既附加又可见。

新 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 模式 让您可以探索、运行和调试测试。 配备内置的 watch 模式。

Playwright UI Mode

使用新标志 --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 用于配置项目之间的依赖关系。

    使用依赖项允许全局设置生成 traces 和其他工件,请参阅测试报告中的设置步骤等。

    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() 确保 locator 指向与视口相交的元素,根据 intersection observer 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 });

其他

  • trace viewer 中的 DOM 快照现在可以在单独的窗口中打开。
  • 新方法 defineConfig 用于 playwright.config 中。
  • 方法 route.fetch() 的新选项 maxRedirects
  • Playwright 现在支持 Debian 11 arm64。
  • 官方 docker 镜像 现在包含 Node 18 而不是 Node 16。

⚠️ 组件测试中的重大更改

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

组件测试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 调用

// After

import { defineConfig, devices } from '@playwright/experimental-ct-react';
export default defineConfig({
// ... config goes here ...
});

浏览器版本

  • 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 => {
    // 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() 现在按 value 或 label 匹配

    <select multiple>
    <option value="red">Red</div>
    <option value="green">Green</div>
    <option value="blue">Blue</div>
    </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.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 中在光标处录制。 您可以运行测试,将光标放在测试末尾,然后继续生成测试。

New VSCode Extension

  • VSCode 中的实时 Locators。 您可以在 VSCode 中悬停和编辑 locators,以在打开的浏览器中突出显示它们。
  • CodeGen 中的实时 Locators。 使用 “Explore” 工具为页面上的任何元素生成 locator。

Locator Explorer

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

Dark Theme

测试运行器

新 API

浏览器版本

  • Chromium 108.0.5359.29
  • Mozilla Firefox 106.0
  • WebKit 16.4

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

  • Google Chrome 107
  • Microsoft Edge 107

版本 1.27

Locators

使用这些新 API,编写 locators 是一种乐趣

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 中宣布的那样,从 2022 年 12 月起将不再支持 Ubuntu 18。 除此之外,从下一个 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.net.cn', {
waitUntil: 'domcontentloaded',
});

在 1.26 之前,这将等待所有 iframes 触发 DOMContentLoaded 事件。

为了与网络规范保持一致,'domcontentloaded' 值仅等待目标 frame 触发 'DOMContentLoaded' 事件。使用 waitUntil: 'load' 可以等待所有 iframe 加载完成。

浏览器版本

  • 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() 现在返回 step 函数的值

    test('should work', async ({ page }) => {
    const pageTitle = await test.step('get title', async () => {
    await page.goto('https://playwright.net.cn');
    return await page.title();
    });
    console.log(pageTitle);
    });
  • 新增 test.describe.fixme()

  • 新的 'interrupted' 测试状态。

  • 通过 CLI 标志启用 tracing: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: 'https://127.0.0.1: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 | ✅ | ✅ | ✅ |

🕵️ 匿名 Describe

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

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

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

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

🧩 组件测试更新

Playwright 1.24 组件测试引入了 beforeMountafterMount 钩子。使用这些钩子来配置您的应用程序以进行测试。

例如,这可以用于在 Vue.js 中设置 App router

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: {
/* anything to configure your app */
}
});
});
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>, {
// Pass mock value from test into `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 }) => {
// Before mount, redefine useRouter to return mock value from test.
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' }
});
// ... do stuff ...
await context.close();

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

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

我们的文档中阅读更多信息。

高级路由

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

考虑以下示例

// 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() 也参与路由,并且可以被推迟。

Web-First 断言更新

组件测试更新

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

其他

  • 如果您的服务工作线程妨碍了您,您现在可以使用新的上下文选项 serviceWorkers 轻松禁用它

    playwright.config.ts
    export default {
    use: {
    serviceWorkers: 'block',
    }
    };
  • recordHar 上下文选项使用 .zip 路径会自动压缩生成的 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

⚠️ 破坏性更改 ⚠️

如果对指定 url 的请求具有以下任何 HTTP 状态代码,则 WebServer 现在被认为是“就绪”状态

  • 200-299
  • 300-399(新增)
  • 400401402403(新增)

版本 1.22

亮点

  • 组件测试(预览)

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

    以下是一个典型的组件测试示例

    App.spec.tsx
    import { 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,用于过滤现有的 locator

    const buttons = page.locator('role=button');
    // ...
    const submitButton = buttons.filter({ hasText: 'Submit' });
    await submitButton.click();
  • 新的 web-first 断言 expect(page).toHaveScreenshot()expect(locator).toHaveScreenshot(),它们等待屏幕截图稳定并增强测试可靠性。

    新的断言具有屏幕截图特定的默认值,例如

    • 禁用动画
    • 使用 CSS scale 选项
    await page.goto('https://playwright.net.cn');
    await expect(page).toHaveScreenshot();

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

版本 1.21

亮点

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

    // Click a button with accessible name "log in"
    await page.locator('role=button[name="log in"]').click();

    我们的文档中阅读更多信息。

  • page.screenshot() 中新的 scale 选项,用于缩小屏幕截图尺寸。

  • 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() 等。在我们的文档中阅读更多信息。

行为变更

  • 默认情况下,在运行 TypeScript 测试时启用 ESM 支持。不再需要 PLAYWRIGHT_EXPERIMENTAL_TS_ESM 环境变量。
  • mcr.microsoft.com/playwright docker 镜像不再包含 Python。请使用 mcr.microsoft.com/playwright/python 作为预装 Python 的 Playwright 就绪 docker 镜像。
  • 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();
  • 用于使用 expect().toMatchSnapshot() 进行细粒度屏幕截图比较的新 maxDiffPixelsmaxDiffPixelRatio 选项

    expect(await page.screenshot()).toMatchSnapshot({
    maxDiffPixels: 27, // allow no more than 27 different pixels.
    });

    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 现在支持软断言。失败的软断言

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

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

    我们的文档中阅读更多信息

  • 您现在可以为 expectexpect.soft 函数指定一个自定义 expect 消息作为第二个参数,例如

    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 全局 Setup 中潜在的破坏性更改

此更改不太可能影响您,如果您的测试继续像以前一样运行,则无需采取任何措施。

我们注意到,在极少数情况下,要执行的测试集是在全局 setup 中通过环境变量配置的。我们还注意到一些应用程序在全局 teardown 中对 reporter 的输出进行后处理。如果您正在执行这两项操作之一,请了解更多信息

浏览器版本

  • Chromium 100.0.4863.0
  • Mozilla Firefox 96.0.1
  • WebKit 15.4

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

  • Google Chrome 98
  • Microsoft Edge 98

版本 1.18

Locator 改进

测试 API 改进

改进的 TypeScript 支持

  1. Playwright Test 现在遵守 tsconfig.jsonbaseUrlpaths,因此您可以使用别名
  2. 有一个新的环境变量 PW_EXPERIMENTAL_TS_ESM,允许在您的 TS 代码中导入 ESM 模块,而无需编译步骤。当您导入 esm 模块时,不要忘记 .js 后缀。按如下方式运行您的测试
npm i --save-dev @playwright/[email protected]
PW_EXPERIMENTAL_TS_ESM=1 npx playwright test

创建 Playwright

npm init playwright 命令现在通常可供您使用

# Run from your project's root directory
npm init playwright@latest
# Or create a new project
npm init playwright@latest new-project

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

新 API 和更改

破坏性更改:自定义配置选项

自定义配置选项是使用不同值参数化项目的便捷方法。在本指南中了解更多信息。

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

// 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',
},
};

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

// 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',
},
};

浏览器版本

  • 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 的 locator。Frame locators 捕获了检索 iframe 以及随后在 iframe 中定位元素的逻辑。Frame locators 默认是严格模式,将等待 iframe 出现,并且可以用于 Web-First 断言。

Graphics

可以使用 page.frameLocator()locator.frameLocator() 方法创建 Frame locators。

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

我们的文档中阅读更多信息。

Trace Viewer 更新

Playwright Trace Viewer 现在在线可用,网址为 https://trace.playwright.dev!只需拖放您的 trace.zip 文件即可检查其内容。

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

  • Playwright Test traces 现在默认包含 sources(可以使用 tracing 选项关闭这些 sources)
  • Trace Viewer 现在显示测试名称
  • 新的 trace 元数据选项卡,包含浏览器详细信息
  • 快照现在具有 URL 栏

image

HTML 报告更新

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

image

Ubuntu ARM64 支持 + 更多

  • Playwright 现在支持 Ubuntu 20.04 ARM64。您现在可以在 Apple M1 和 Raspberry Pi 上的 Docker 中运行 Playwright 测试。

  • 您现在可以使用 Playwright 在 Linux 上安装稳定版本的 Edge

    npx playwright install msedge

新 API

版本 1.16

🎭 Playwright Test

API 测试

Playwright 1.16 引入了新的 API 测试,使您可以直接从 Node.js 向服务器发送请求!现在您可以

  • 测试您的服务器 API
  • 在测试中访问 Web 应用程序之前准备服务器端状态
  • 在浏览器中运行某些操作后验证服务器端后置条件

要代表 Playwright 的 Page 发出请求,请使用新的 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 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 测试指南中阅读更多相关信息。

响应拦截

现在可以通过将 API 测试请求拦截 相结合来进行响应拦截。

例如,我们可以模糊页面上的所有图像

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

响应拦截中阅读更多信息。

新的 HTML reporter

使用 --reporter=htmlplaywright.config.ts 文件中的 reporter 条目试用新的 HTML reporter

$ npx playwright test --reporter=html

HTML reporter 包含有关测试及其失败的所有信息,包括显示 trace 和图像 artifacts。

html reporter

我们的 reporters 中阅读更多信息。

🎭 Playwright Library

locator.waitFor

等待 locator 解析为具有给定状态的单个元素。默认为 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 Trace Viewer

  • trace viewer 内的 web-first 断言
  • 使用 npx playwright show-trace 运行 trace viewer,并将 trace 文件拖放到 trace viewer PWA
  • API 测试已与 trace viewer 集成
  • 更好地可视化操作目标的归属

Trace Viewer 中阅读更多信息。

浏览器版本

  • Chromium 97.0.4666.0
  • Mozilla Firefox 93.0
  • WebKit 15.4

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

  • Google Chrome 94
  • Microsoft Edge 94

版本 1.15

🎭 Playwright Library

🖱️ 鼠标滚轮

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

📜 新的 Headers API

以前无法获取响应的多个 header 值。现在可以实现这一点,并且提供了额外的辅助函数

🌈 Forced-Colors 模拟

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

新 API

🎭 Playwright Test

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

test.describe.parallel('group', () => {
test('runs in parallel 1', async ({ page }) => {
});
test('runs in parallel 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 Library

⚡️ 新的“strict”模式

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

strict: true 传递到您的操作调用中以选择启用。

// This will throw if you have more than one button!
await page.click('button', { strict: true });

📍 新的 Locators API

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

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

此外,locators 默认是“strict”模式

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

文档中了解更多信息。

🧩 实验性的 ReactVue 选择器引擎

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

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

react selectors 文档vue selectors 文档 中了解更多信息。

✨ 新的 nthvisible 选择器引擎

  • nth 选择器引擎等同于 :nth-match 伪类,但可以与其他选择器引擎结合使用。
  • visible 选择器引擎等同于 :visible 伪类,但可以与其他选择器引擎结合使用。
// 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 Test

✅ Web-First Assertions

expect 现在支持许多新的 Web 优先断言。

考虑以下示例

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('Log in', async () => {
// ...
});
await test.step('news feed', async () => {
// ...
});
});

步骤信息在 reporters API 中公开。

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

要在测试期间启动服务器,请在配置文件中使用 webServer 选项。服务器将等待给定的 url 可用,然后再运行测试,并且在创建上下文时,该 url 将作为 baseURL 传递给 Playwright。

playwright.config.ts
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,
},
});

文档中了解更多信息。

浏览器版本

  • Chromium 94.0.4595.0
  • Mozilla Firefox 91.0
  • WebKit 15.0

版本 1.13

Playwright Test

Playwright

工具

  • 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 集成作为可扩展的 fixtures。

安装

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.net.cn/');
const name = await page.innerText('.navbar__title');
expect(name).toBe('Playwright');
});

运行中

npx playwright test

👉 在 Playwright Test 文档中阅读更多内容。

🧟‍♂️ 推出 Playwright Trace 查看器

Playwright Trace 查看器是一个新的 GUI 工具,可帮助在脚本运行后探索记录的 Playwright 跟踪。Playwright 跟踪使您可以检查

  • 每个 Playwright 操作前后的页面 DOM
  • 每个 Playwright 操作前后的页面渲染
  • 脚本执行期间的浏览器网络

跟踪是使用新的 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.net.cn');

// Stop tracing and export it into a zip archive.
await context.tracing.stop({ path: 'trace.zip' });

稍后使用 Playwright CLI 检查跟踪

npx playwright show-trace trace.zip

这将打开以下 GUI

image

👉 在 trace viewer 文档中阅读更多内容。

浏览器版本

  • Chromium 93.0.4530.0
  • Mozilla Firefox 89.0
  • WebKit 14.2

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

  • Google Chrome 91
  • Microsoft Edge 91

新 API

版本 1.11

🎥 新视频:Playwright: A New Test Automation Framework for the Modern 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
  • 在有头模式下使用 page.pause() 暂停脚本执行。暂停页面会启动 Playwright Inspector 以进行调试。
  • CSS 选择器的新 has-text 伪类:has-text("example") 匹配任何在其内部(可能在子元素或后代元素中)包含 "example" 的元素。请参阅更多示例
  • 页面对话框现在在执行期间会自动关闭,除非配置了 dialog 事件的侦听器。了解更多关于此的信息。
  • Playwright for Python 现在稳定了,具有惯用的 snake case 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 bindings 并驾齐驱。
  • 浏览器存储 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