Skip to main content

发行说明

1.43 版本

¥Version 1.43

新 API

¥New APIs

  • 方法 browserContext.clearCookies() 现在支持过滤器以仅删除一些 cookie。

    ¥Method browserContext.clearCookies() now supports filters to remove only some cookies.

    // Clear all cookies.
    await context.clearCookies();
    // New: clear cookies with a particular name.
    await context.clearCookies({ name: 'session-id' });
    // New: clear cookies for a particular domain.
    await context.clearCookies({ domain: 'my-origin.com' });
  • testOptions.trace 的新模式 retain-on-first-failure。在此模式下,将记录每个测试第一次运行的跟踪,但不会记录退出的跟踪。当测试运行失败时,跟踪文件被保留,否则被删除。

    ¥New mode retain-on-first-failure for testOptions.trace. In this mode, trace is recorded for the first run of each test, but not for retires. When test run fails, the trace file is retained, otherwise it is removed.

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

    export default defineConfig({
    use: {
    trace: 'retain-on-first-failure',
    },
    });
  • 新属性 testInfo.tags 在测试执行期间公开测试标签。

    ¥New property testInfo.tags exposes test tags during test execution.

    test('example', async ({ page }) => {
    console.log(test.info().tags);
    });
  • 新方法 locator.contentFrame()Locator 对象转换为 FrameLocator。当你在某处获得了 Locator 对象,并且稍后想要与框架内的内容进行交互时,这会很有用。

    ¥New method locator.contentFrame() converts a Locator object to a FrameLocator. This can be useful when you have a Locator object obtained somewhere, and later on would like to interact with the content inside the frame.

    const locator = page.locator('iframe[name="embedded"]');
    // ...
    const frameLocator = locator.contentFrame();
    await frameLocator.getByRole('button').click();
  • 新方法 frameLocator.owner()FrameLocator 对象转换为 Locator。当你在某处获得了 FrameLocator 对象,并且稍后想要与 iframe 元素进行交互时,这会很有用。

    ¥New method frameLocator.owner() converts a FrameLocator object to a Locator. This can be useful when you have a FrameLocator object obtained somewhere, and later on would like to interact with the iframe element.

    const frameLocator = page.frameLocator('iframe[name="embedded"]');
    // ...
    const locator = frameLocator.owner();
    await expect(locator).toBeVisible();

用户界面模式更新

¥UI Mode Updates

Playwright UI Mode

  • 查看测试列表中的标签。

    ¥See tags in the test list.

  • 通过输入 @fast 或单击标签本身来按标签过滤。

    ¥Filter by tags by typing @fast or clicking on the tag itself.

  • 新的快捷键:

    ¥New shortcuts:

    • "F5" 运行测试。

      ¥"F5" to run tests.

    • "移 F5" 停止运行测试。

      ¥"Shift F5" to stop running tests.

    • "Ctrl`" 切换测试输出。

      ¥"Ctrl `" to toggle test output.

浏览器版本

¥Browser Versions

  • Chromium 124.0.6367.8

  • 火狐浏览器 124.0

    ¥Mozilla Firefox 124.0

  • 网络工具包 17.4

    ¥WebKit 17.4

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

¥This version was also tested against the following stable channels:

  • 谷歌浏览器 123

    ¥Google Chrome 123

  • 微软边缘 123

    ¥Microsoft Edge 123

1.42 版本

¥Version 1.42

新 API

¥New APIs

  • 新方法 page.addLocatorHandler() 注册一个回调,当指定元素变得可见时将调用该回调,并且可能会阻止 Playwright 操作。回调可以摆脱覆盖。下面是一个在 cookie 对话框出现时关闭它的示例:

    ¥New method page.addLocatorHandler() registers a callback that will be invoked when specified element becomes visible and may block Playwright actions. The callback can get rid of the overlay. Here is an example that closes a cookie dialog when it appears:

// 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):

    ¥New syntax for adding tags to the tests (@-tokens in the test title are still supported):

test('test customer login', {
tag: ['@fast', '@login'],
}, async ({ page }) => {
// ...
});

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

¥Use --grep command line option to run only tests with certain tags.

npx playwright test --grep @fast
  • --project 命令行 flag 现在支持 '*' 通配符:

    ¥--project command line flag now supports '*' wildcard:

npx playwright test --project='*mobile*'
test('test full report', {
annotation: [
{ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/23180' },
{ type: 'docs', description: 'https://playwright.nodejs.cn/docs/test-annotations#tag-tests' },
],
}, async ({ page }) => {
// ...
});

公告

¥Announcements

  • ⚠️ Ubuntu 18 不再受支持。

    ¥⚠️ Ubuntu 18 is not supported anymore.

浏览器版本

¥Browser Versions

  • Chromium 123.0.6312.4

  • 火狐浏览器 123.0

    ¥Mozilla Firefox 123.0

  • 网络工具包 17.4

    ¥WebKit 17.4

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

¥This version was also tested against the following stable channels:

  • 谷歌浏览器 122

    ¥Google Chrome 122

  • 微软边缘 123

    ¥Microsoft Edge 123

1.41 版本

¥Version 1.41

新 API

¥New APIs

浏览器版本

¥Browser Versions

  • Chromium 121.0.6167.57

  • 火狐浏览器 121.0

    ¥Mozilla Firefox 121.0

  • 网络工具包 17.4

    ¥WebKit 17.4

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

¥This version was also tested against the following stable channels:

  • 谷歌浏览器 120

    ¥Google Chrome 120

  • 微软 Edge 120

    ¥Microsoft Edge 120

1.40 版本

¥Version 1.40

测试生成器更新

¥Test Generator Update

Playwright Test Generator

生成断言的新工具:

¥New tools to generate assertions:

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

¥Here is an example of a generated test with assertions:

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

test('test', async ({ page }) => {
await page.goto('https://playwright.nodejs.cn/');
await page.getByRole('link', { name: 'Get started' }).click();
await expect(page.getByLabel('Breadcrumbs').getByRole('list')).toContainText('Installation');
await expect(page.getByLabel('Search')).toBeVisible();
await page.getByLabel('Search').click();
await page.getByPlaceholder('Search docs').fill('locator');
await expect(page.getByPlaceholder('Search docs')).toHaveValue('locator');
});

新 API

¥New APIs

其他变更

¥Other Changes

浏览器版本

¥Browser Versions

  • Chromium 120.0.6099.28

  • 火狐浏览器 119.0

    ¥Mozilla Firefox 119.0

  • 网络工具包 17.4

    ¥WebKit 17.4

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

¥This version was also tested against the following stable channels:

  • 谷歌浏览器 119

    ¥Google Chrome 119

  • 微软 Edge 119

    ¥Microsoft Edge 119

1.39 版本

¥Version 1.39

根据你的期望添加自定义匹配器

¥Add custom matchers to your expect

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

¥You can extend Playwright assertions by providing custom matchers. These matchers will be available on the expect object.

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

请参阅文档 完整的例子

¥See the documentation for a full example.

合并测试夹具

¥Merge test fixtures

你现在可以合并来自多个文件或模块的测试装置:

¥You can now merge test fixtures from multiple files or modules:

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

合并自定义期望匹配器

¥Merge custom expect matchers

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

¥You can now merge custom expect matchers from multiple files or modules:

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

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

¥Hide implementation details: box test steps

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

¥You can mark a test.step() as "boxed" so that errors inside it point to the step call site.

async function login(page) {
await test.step('login', async () => {
// ...
}, { box: true }); // Note the "box" option here.
}
Error: Timed out 5000ms waiting for expect(locator).toBeVisible()
... error details omitted ...

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

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

¥See test.step() documentation for a full example.

新 API

¥New APIs

浏览器版本

¥Browser Versions

  • Chromium 119.0.6045.9

  • 火狐浏览器 118.0.1

    ¥Mozilla Firefox 118.0.1

  • 网络工具包 17.4

    ¥WebKit 17.4

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

¥This version was also tested against the following stable channels:

  • 谷歌浏览器 118

    ¥Google Chrome 118

  • 微软 Edge 118

    ¥Microsoft Edge 118

1.38 版本

¥Version 1.38

用户界面模式更新

¥UI Mode Updates

Playwright UI Mode

  1. 放大时间范围。

    ¥Zoom into time range.

  2. 网络面板重新设计。

    ¥Network panel redesign.

新 API

¥New APIs

弃用

¥Deprecations

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

¥Breaking Changes: Playwright no longer downloads browsers automatically

注意:如果你使用的是 @playwright/test 软件包,此更改不会影响你。

¥Note: If you are using @playwright/test package, this change does not affect you.

Playwright 建议使用 @playwright/test 包并通过 npx playwright install 命令下载浏览器。如果你遵循此建议,那么对你来说没有任何改变。

¥Playwright recommends to use @playwright/test package and download browsers via npx playwright install command. If you are following this recommendation, nothing has changed for you.

但是,直到 v1.38,安装 playwright 软件包而不是 @playwright/test 确实会自动下载浏览器。现在情况不再是这样,我们建议通过 npx playwright install 命令显式下载浏览器。

¥However, up to v1.38, installing the playwright package instead of @playwright/test did automatically download browsers. This is no longer the case, and we recommend to explicitly download browsers via npx playwright install command.

v1.37 及更早版本

¥v1.37 and earlier

playwright 软件包在 npm install 期间下载浏览器,而 @playwright/test 则没有。

¥playwright package was downloading browsers during npm install, while @playwright/test was not.

v1.38 及更高版本

¥v1.38 and later

playwright@playwright/test 软件包在 npm install 期间不会下载浏览器。

¥playwright and @playwright/test packages do not download browsers during npm install.

推荐迁移

¥Recommended migration

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

¥Run npx playwright install to download browsers after npm install. For example, in your CI configuration:

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

替代迁移选项 - 不建议

¥Alternative migration option - not recommended

添加 @playwright/browser-chromium@playwright/browser-firefox@playwright/browser-webkit 作为依赖。这些软件包在 npm install 期间下载各自的浏览器。确保所有 playwright 包的版本保持同步:

¥Add @playwright/browser-chromium, @playwright/browser-firefox and @playwright/browser-webkit as a dependency. These packages download respective browsers during npm install. Make sure you keep the version of all playwright packages in sync:

// package.json
{
"devDependencies": {
"playwright": "1.38.0",
"@playwright/browser-chromium": "1.38.0",
"@playwright/browser-firefox": "1.38.0",
"@playwright/browser-webkit": "1.38.0"
}
}

浏览器版本

¥Browser Versions

  • Chromium 117.0.5938.62

  • 火狐浏览器 117.0

    ¥Mozilla Firefox 117.0

  • 网络工具包 17.0

    ¥WebKit 17.0

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

¥This version was also tested against the following stable channels:

  • 谷歌浏览器 116

    ¥Google Chrome 116

  • 微软 Edge 116

    ¥Microsoft Edge 116

1.37 版本

¥Version 1.37

新的 npx playwright merge-reports 工具

¥New npx playwright merge-reports tool

如果你在多个分片上运行测试,你现在可以使用新的 merge-reports CLI 工具将所有报告合并到单个 HTML 报告(或任何其他报告)中。

¥If you run tests on multiple shards, you can now merge all reports in a single HTML report (or any other report) using the new merge-reports CLI tool.

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

¥Using merge-reports tool requires the following steps:

  1. 在 CI 上运行时将新的 "blob" 报告器添加到配置中:

    ¥Adding a new "blob" reporter to the config when running on CI:

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

    "blob" 报告器将生成 ".zip" 文件,其中包含有关测试运行的所有信息。

    ¥The "blob" reporter will produce ".zip" files that contain all the information about the test run.

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

    ¥Copying all "blob" reports in a single shared location and running npx playwright merge-reports:

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

阅读 我们的文档 中的更多内容。

¥Read more in our documentation.

📚 Debian 12 Bookworm 支持

¥📚 Debian 12 Bookworm Support

Playwright 现在支持在 x86_64 和 arm64 上运行 Chromium、Firefox 和 WebKit 的 Debian 12 Bookworm。如果你遇到任何问题,请告诉我们!

¥Playwright now supports Debian 12 Bookworm on both x86_64 and arm64 for Chromium, Firefox and WebKit. Let us know if you encounter any issues!

Linux 支持如下所示:

¥Linux support looks like this:

乌班图 20.04乌班图 22.04Debian 11Debian 12
Chromium
WebKit
火狐浏览器

用户界面模式更新

¥UI Mode Updates

  • UI 模式现在尊重项目依赖。你可以通过在项目列表中选中/取消选中依赖来控制要遵循的依赖。

    ¥UI Mode now respects project dependencies. You can control which dependencies to respect by checking/unchecking them in a projects list.

  • 测试的控制台日志现在显示在“控制台”选项卡中。

    ¥Console logs from the test are now displayed in the Console tab.

浏览器版本

¥Browser Versions

  • Chromium 116.0.5845.82

  • 火狐浏览器 115.0

    ¥Mozilla Firefox 115.0

  • 网络工具包 17.0

    ¥WebKit 17.0

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

¥This version was also tested against the following stable channels:

  • 谷歌浏览器 115

    ¥Google Chrome 115

  • 微软 Edge 115

    ¥Microsoft Edge 115

1.36 版本

¥Version 1.36

🏝️ 夏季维护版本。

¥🏝️ Summer maintenance release.

浏览器版本

¥Browser Versions

  • Chromium 115.0.5790.75

  • 火狐浏览器 115.0

    ¥Mozilla Firefox 115.0

  • 网络工具包 17.0

    ¥WebKit 17.0

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

¥This version was also tested against the following stable channels:

  • 谷歌浏览器 114

    ¥Google Chrome 114

  • 微软 Edge 114

    ¥Microsoft Edge 114

1.35 版本

¥Version 1.35

高亮

¥Highlights

  • UI 模式现在可通过新的 "显示跟踪查看器" 按钮在 VSCode Playwright 扩展中使用:

    ¥UI mode is now available in VSCode Playwright extension via a new "Show trace viewer" button:

Playwright UI Mode

Trace Viewer

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

    ¥New option maskColor for methods page.screenshot(), locator.screenshot(), expect(page).toHaveScreenshot() and expect(locator).toHaveScreenshot() to change default masking color:

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

    ¥New uninstall CLI command to uninstall browser binaries:

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

    ¥Both UI mode and trace viewer now could be opened in a browser tab:

    $ npx playwright test --ui-port 0 # open UI mode in a tab on a random port
    $ npx playwright show-trace --port 0 # open trace viewer in tab on a random port

⚠️ 重大变化

¥⚠️ Breaking changes

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

    ¥playwright-core binary got renamed from playwright to playwright-core. So if you use playwright-core CLI, make sure to update the name:

    $ npx playwright-core install # the new way to install browsers when using playwright-core

    此更改不会影响 @playwright/testplaywright 套餐用户。

    ¥This change does not affect @playwright/test and playwright package users.

浏览器版本

¥Browser Versions

  • Chromium 115.0.5790.13

  • 火狐浏览器 113.0

    ¥Mozilla Firefox 113.0

  • 网络工具包 16.4

    ¥WebKit 16.4

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

¥This version was also tested against the following stable channels:

  • 谷歌浏览器 114

    ¥Google Chrome 114

  • 微软 Edge 114

    ¥Microsoft Edge 114

1.34 版本

¥Version 1.34

高亮

¥Highlights

  • UI 模式现在显示步骤、夹具和附件:

    ¥UI Mode now shows steps, fixtures and attachments:

UI Mode attachments

  • 新属性 testProject.teardown 用于指定在此项目和所有依赖目完成后需要运行的项目。拆卸对于清理该项目获取的任何资源很有用。

    ¥New property testProject.teardown to specify a project that needs to run after this and all dependent projects have finished. Teardown is useful to cleanup any resources acquired by this project.

    常见的模式是 setup 依赖与相应的 teardown

    ¥A common pattern would be a setup dependency with a corresponding 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 用于创建具有自己的默认值(例如 timeoutsoft)的预配置期望实例。

    ¥New method expect.configure to create pre-configured expect instance with its own defaults such as timeout and soft.

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

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

    ¥New options stderr and stdout in testConfig.webServer to configure output handling:

    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() 以创建与两个定位器匹配的定位器。

    ¥New locator.and() to create a locator that matches both locators.

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

    ¥New events browserContext.on('console') and browserContext.on('dialog') to subscribe to any dialogs and console messages from any page from the given browser context. Use the new methods consoleMessage.page() and dialog.page() to pin-point event source.

⚠️ 重大变化

¥⚠️ Breaking changes

  • 如果你同时安装 playwright@playwright/testnpx playwright test 将不再起作用。无需安装两者,因为你始终可以直接从 @playwright/test 导入浏览器自动化 API:

    ¥npx playwright test no longer works if you install both playwright and @playwright/test. There's no need to install both, since you can always import browser automation APIs from @playwright/test directly:

    automation.ts
    import { chromium, firefox, webkit } from '@playwright/test';
    /* ... */
  • Node.js 14 自 2023 年 4 月 30 日 已达到使用寿命 起不再受支持。

    ¥Node.js 14 is no longer supported since it reached its end-of-life on April 30, 2023.

浏览器版本

¥Browser Versions

  • Chromium 114.0.5735.26

  • 火狐浏览器 113.0

    ¥Mozilla Firefox 113.0

  • 网络工具包 16.4

    ¥WebKit 16.4

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

¥This version was also tested against the following stable channels:

  • 谷歌浏览器 113

    ¥Google Chrome 113

  • 微软 Edge 113

    ¥Microsoft Edge 113

1.33 版本

¥Version 1.33

定位器更新

¥Locators Update

  • 使用 locator.or() 创建与两个定位器之一匹配的定位器。考虑这样一个场景:你想要单击 "新邮件" 按钮,但有时会显示安全设置对话框。在这种情况下,你可以等待 "新邮件" 按钮或对话框并进行相应操作:

    ¥Use locator.or() to create a locator that matches either of the two locators. Consider a scenario where you'd like to click on a "New email" button, but sometimes a security settings dialog shows up instead. In this case, you can wait for either a "New email" button, or a dialog and act accordingly:

    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 来查找不符合某些条件的元素。

    ¥Use new options hasNot and hasNotText in locator.filter() to find elements that do not match certain conditions.

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

    ¥Use new web-first assertion expect(locator).toBeAttached() to ensure that the element is present in the page's DOM. Do not confuse with the expect(locator).toBeVisible() that ensures that element is both attached & visible.

新 API

¥New APIs

⚠️ 重大改变

¥⚠️ Breaking change

  • mcr.microsoft.com/playwright:v1.33.0 现在提供基于 Ubuntu Jammy 的 Playwright 映像。要使用基于焦点的图片,请改用 mcr.microsoft.com/playwright:v1.33.0-focal

    ¥The mcr.microsoft.com/playwright:v1.33.0 now serves a Playwright image based on Ubuntu Jammy. To use the focal-based image, please use mcr.microsoft.com/playwright:v1.33.0-focal instead.

浏览器版本

¥Browser Versions

  • Chromium 113.0.5672.53

  • 火狐浏览器 112.0

    ¥Mozilla Firefox 112.0

  • 网络工具包 16.4

    ¥WebKit 16.4

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

¥This version was also tested against the following stable channels:

  • 谷歌浏览器 112

    ¥Google Chrome 112

  • 微软 Edge 112

    ¥Microsoft Edge 112

1.32 版本

¥Version 1.32

UI 模式简介(预览)

¥Introducing UI Mode (preview)

新的 用户界面模式 允许你探索、运行和调试测试。带有内置监视模式。

¥New UI Mode lets you explore, run and debug tests. Comes with a built-in watch mode.

Playwright UI Mode

使用新标志 --ui

¥Engage with a new flag --ui:

npx playwright test --ui

新 API

¥New APIs

⚠️ 组件测试的重大变化

¥⚠️ Breaking change in component tests

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

¥Note: component tests only, does not affect end-to-end tests.

  • @playwright/experimental-ct-react 现在仅支持 React 18。

    ¥@playwright/experimental-ct-react now supports React 18 only.

  • 如果你使用 React 16 或 17 运行组件测试,请将 @playwright/experimental-ct-react 替换为 @playwright/experimental-ct-react17

    ¥If you're running component tests with React 16 or 17, please replace @playwright/experimental-ct-react with @playwright/experimental-ct-react17.

浏览器版本

¥Browser Versions

  • Chromium 112.0.5615.29

  • 火狐浏览器 111.0

    ¥Mozilla Firefox 111.0

  • 网络工具包 16.4

    ¥WebKit 16.4

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

¥This version was also tested against the following stable channels:

  • 谷歌浏览器 111

    ¥Google Chrome 111

  • 微软 Edge 111

    ¥Microsoft Edge 111

1.31 版本

¥Version 1.31

新 API

¥New APIs

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

    ¥New property testProject.dependencies to configure dependencies between projects.

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

    ¥Using dependencies allows global setup to produce traces and other artifacts, see the setup steps in the test report and more.

    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'],
    },
    ],
    });
  • 根据 交集监视器 API,新断言 expect(locator).toBeInViewport() 确保定位器指向与视口相交的元素。

    ¥New assertion expect(locator).toBeInViewport() ensures that locator points to an element that intersects viewport, according to the 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 });

杂项

¥Miscellaneous

  • 现在可以在单独的窗口中打开跟踪查看器中的 DOM 快照。

    ¥DOM snapshots in trace viewer can be now opened in a separate window.

  • 新方法 defineConfig 将在 playwright.config 中使用。

    ¥New method defineConfig to be used in playwright.config.

  • 方法 route.fetch() 的新选项 Route.fetch.maxRedirects

    ¥New option Route.fetch.maxRedirects for method route.fetch().

  • Playwright 现在支持 Debian 11 arm64。

    ¥Playwright now supports Debian 11 arm64.

  • 官方 docker 图片 现在包括 Node 18,而不是 Node 16。

    ¥Official docker images now include Node 18 instead of Node 16.

⚠️ 组件测试的重大变化

¥⚠️ Breaking change in component tests

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

¥Note: component tests only, does not affect end-to-end tests.

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

¥playwright-ct.config configuration file for component testing now requires calling defineConfig.

// Before

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

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

¥Replace config variable definition with defineConfig call:

// After

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

浏览器版本

¥Browser Versions

  • Chromium 111.0.5563.19

  • 火狐浏览器 109.0

    ¥Mozilla Firefox 109.0

  • 网络工具包 16.4

    ¥WebKit 16.4

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

¥This version was also tested against the following stable channels:

  • 谷歌浏览器 110

    ¥Google Chrome 110

  • 微软 Edge 110

    ¥Microsoft Edge 110

1.30 版本

¥Version 1.30

浏览器版本

¥Browser Versions

  • Chromium 110.0.5481.38

  • 火狐浏览器 108.0.2

    ¥Mozilla Firefox 108.0.2

  • 网络工具包 16.4

    ¥WebKit 16.4

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

¥This version was also tested against the following stable channels:

  • 谷歌浏览器 109

    ¥Google Chrome 109

  • 微软 Edge 109

    ¥Microsoft Edge 109

1.29 版本

¥Version 1.29

新 API

¥New APIs

  • route.fulfill() 的新方法 route.fetch() 和新选项 json

    ¥New method route.fetch() and new option json for route.fulfill():

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

    ¥New method locator.all() to iterate over all matching elements:

    // Check all checkboxes!
    const checkboxes = page.getByRole('checkbox');
    for (const checkbox of await checkboxes.all())
    await checkbox.check();
  • locator.selectOption() 现在按值或标签匹配:

    ¥locator.selectOption() matches now by value or label:

    <select multiple>
    <option value="red">Red</div>
    <option value="green">Green</div>
    <option value="blue">Blue</div>
    </select>
    await element.selectOption('Red');
  • 重试代码块,直到所有断言都通过:

    ¥Retry blocks of code until all assertions pass:

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

    阅读 我们的文档 中的更多内容。

    ¥Read more in our documentation.

  • 测试失败时自动捕获全页屏幕截图:

    ¥Automatically capture full page screenshot on test failure:

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

杂项

¥Miscellaneous

浏览器版本

¥Browser Versions

  • Chromium 109.0.5414.46

  • 火狐浏览器 107.0

    ¥Mozilla Firefox 107.0

  • 网络工具包 16.4

    ¥WebKit 16.4

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

¥This version was also tested against the following stable channels:

  • 谷歌浏览器 108

    ¥Google Chrome 108

  • 微软 Edge 108

    ¥Microsoft Edge 108

1.28 版本

¥Version 1.28

Playwright 工具

¥Playwright Tools

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

    ¥Record at Cursor in VSCode. You can run the test, position the cursor at the end of the test and continue generating the test.

New VSCode Extension

  • VSCode 中的实时定位器。你可以将鼠标悬停在 VSCode 中并编辑定位器,以使其在打开的浏览器中高亮。

    ¥Live Locators in VSCode. You can hover and edit locators in VSCode to get them highlighted in the opened browser.

  • CodeGen 中的实时定位器。使用 "探索" 工具为页面上的任何元素生成定位器。

    ¥Live Locators in CodeGen. Generate a locator for any element on the page using "Explore" tool.

Locator Explorer

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

    ¥Codegen and Trace Viewer Dark Theme. Automatically picked up from operating system settings.

Dark Theme

测试运行器

¥Test Runner

新 API

¥New APIs

浏览器版本

¥Browser Versions

  • Chromium 108.0.5359.29

  • 火狐浏览器 106.0

    ¥Mozilla Firefox 106.0

  • 网络工具包 16.4

    ¥WebKit 16.4

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

¥This version was also tested against the following stable channels:

  • 谷歌浏览器 107

    ¥Google Chrome 107

  • 微软 Edge 107

    ¥Microsoft Edge 107

1.27 版本

¥Version 1.27

定位器

¥Locators

使用这些新的 API 编写定位器是一种乐趣:

¥With these new APIs writing locators is a joy:

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 类。

¥All the same methods are also available on Locator, FrameLocator and Frame classes.

其他亮点

¥Other highlights

  • playwright.config.ts 中的 workers 选项现在接受百分比字符串以使用某些可用的 CPU。你也可以在命令行中传递它:

    ¥workers option in the playwright.config.ts now accepts a percentage string to use some of the available CPUs. You can also pass it in the command line:

    npx playwright test --workers=20%
  • html 报告器的新选项 hostport

    ¥New options host and port for the html reporter.

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

    export default defineConfig({
    reporter: [['html', { host: 'localhost', port: '9223' }]],
    });
  • 新字段 FullConfig.configFile 可用于测试报告器,指定配置文件的路径(如果有)。

    ¥New field FullConfig.configFile is available to test reporters, specifying the path to the config file if any.

  • 正如 v1.25 中所宣布的,自 2022 年 12 月起将不再支持 Ubuntu 18。除此之外,从下一个 Playwright 版本开始,Ubuntu 18 将不再有 WebKit 更新。

    ¥As announced in v1.25, Ubuntu 18 will not be supported as of Dec 2022. In addition to that, there will be no WebKit updates on Ubuntu 18 starting from the next Playwright release.

行为改变

¥Behavior Changes

  • 具有空值的 expect(locator).toHaveAttribute() 不再与缺失的属性匹配。例如,当 button 没有 disabled 属性时,以下代码片段将会成功。

    ¥expect(locator).toHaveAttribute() with an empty value does not match missing attribute anymore. For example, the following snippet will succeed when button does not have a disabled attribute.

    await expect(page.getByRole('button')).toHaveAttribute('disabled', '');
  • 命令行选项 --grep--grep-invert 之前错误地忽略了配置中指定的 grepgrepInvert 选项。现在所有这些都一起应用。

    ¥Command line options --grep and --grep-invert previously incorrectly ignored grep and grepInvert options specified in the config. Now all of them are applied together.

浏览器版本

¥Browser Versions

  • Chromium 107.0.5304.18

  • 火狐浏览器 105.0.1

    ¥Mozilla Firefox 105.0.1

  • 网络工具包 16.0

    ¥WebKit 16.0

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

¥This version was also tested against the following stable channels:

  • 谷歌浏览器 106

    ¥Google Chrome 106

  • 微软 Edge 106

    ¥Microsoft Edge 106

1.26 版本

¥Version 1.26

断言

¥Assertions

其他亮点

¥Other highlights

  • 用于 apiRequestContext.get() 和其他限制重定向计数的新选项 maxRedirects

    ¥New option maxRedirects for apiRequestContext.get() and others to limit redirect count.

  • 新的命令行标志 --pass-with-no-tests 允许测试套件在未找到文件时通过。

    ¥New command-line flag --pass-with-no-tests that allows the test suite to pass when no files are found.

  • 新的命令行标志 --ignore-snapshots 可跳过快照预期,例如 expect(value).toMatchSnapshot()expect(page).toHaveScreenshot()

    ¥New command-line flag --ignore-snapshots to skip snapshot expectations, such as expect(value).toMatchSnapshot() and expect(page).toHaveScreenshot().

行为改变

¥Behavior Change

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

¥A bunch of Playwright APIs already support the waitUntil: 'domcontentloaded' option. For example:

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

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

¥Prior to 1.26, this would wait for all iframes to fire the DOMContentLoaded event.

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

¥To align with web specification, the 'domcontentloaded' value only waits for the target frame to fire the 'DOMContentLoaded' event. Use waitUntil: 'load' to wait for all iframes.

浏览器版本

¥Browser Versions

  • Chromium 106.0.5249.30

  • 火狐浏览器 104.0

    ¥Mozilla Firefox 104.0

  • 网络工具包 16.0

    ¥WebKit 16.0

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

¥This version was also tested against the following stable channels:

  • 谷歌浏览器 105

    ¥Google Chrome 105

  • 微软 Edge 105

    ¥Microsoft Edge 105

1.25 版本

¥Version 1.25

VSCode 扩展

¥VSCode Extension

  • 监视实时运行的测试并保持开发工具打开。

    ¥Watch your tests running live & keep devtools open.

  • 选择选择器。

    ¥Pick selector.

  • 从当前页面状态记录新测试。

    ¥Record new test from current page state.

vscode extension screenshot

测试运行器

¥Test Runner

  • test.step() 现在返回阶跃函数的值:

    ¥test.step() now returns the value of the step function:

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

    ¥Added test.describe.fixme().

  • 新的 'interrupted' 测试状态。

    ¥New 'interrupted' test status.

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

    ¥Enable tracing via CLI flag: npx playwright test --trace=on.

公告

¥Announcements

  • 🎁 我们现在发布 Ubuntu 22.04 Jammy Jellyfish docker 镜像:mcr.microsoft.com/playwright:v1.34.0-jammy

    ¥🎁 We now ship Ubuntu 22.04 Jammy Jellyfish docker image: mcr.microsoft.com/playwright:v1.34.0-jammy.

  • 🪦 这是支持 macOS 10.15 的最后一个版本(自 1.21 起已弃用)。

    ¥🪦 This is the last release with macOS 10.15 support (deprecated as of 1.21).

  • 🪦 这是支持 Node.js 12 的最后一个版本,我们建议升级到 Node.js LTS (16)。

    ¥🪦 This is the last release with Node.js 12 support, we recommend upgrading to Node.js LTS (16).

  • ⚠️ Ubuntu 18 现已弃用,自 2022 年 12 月起将不再受支持。

    ¥⚠️ Ubuntu 18 is now deprecated and will not be supported as of Dec 2022.

浏览器版本

¥Browser Versions

  • Chromium 105.0.5195.19

  • 火狐浏览器 103.0

    ¥Mozilla Firefox 103.0

  • 网络工具包 16.0

    ¥WebKit 16.0

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

¥This version was also tested against the following stable channels:

  • 谷歌浏览器 104

    ¥Google Chrome 104

  • 微软 Edge 104

    ¥Microsoft Edge 104

1.24 版本

¥Version 1.24

🌍 playwright.config.ts 中的多个 Web 服务器

¥🌍 Multiple Web Servers in playwright.config.ts

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

¥Launch multiple web servers, databases, or other processes by passing an array of configurations:

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 支持

¥🐂 Debian 11 Bullseye Support

Playwright 现在支持 x86_64 上的 Debian 11 Bullseye,适用于 Chromium、Firefox 和 WebKit。如果你遇到任何问题,请告诉我们!

¥Playwright now supports Debian 11 Bullseye on x86_64 for Chromium, Firefox and WebKit. Let us know if you encounter any issues!

Linux 支持如下所示:

¥Linux support looks like this:

| | 乌班图 20.04 | 乌班图 22.04 | Debian 11 | :--- | :---:| :---:| :---:| :---:| | Chromium | ✅ | ✅ | ✅ | | WebKit | ✅ | ✅ | ✅ | | Firefox | ✅ | ✅ | ✅ |

¥Ubuntu 20.04Ubuntu 22.04Debian 11
Chromium
WebKit
Firefox

🕵️ 匿名描述

¥🕵️ Anonymous Describe

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

¥It is now possible to call test.describe() to create suites without a title. This is useful for giving a group of tests a common option with test.use().

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

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

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

🧩 组件测试更新

¥🧩 Component Tests Update

Playwright 1.24 组件测试引入了 beforeMountafterMount 钩子。使用它们来配置你的应用以进行测试。

¥Playwright 1.24 Component Tests introduce beforeMount and afterMount hooks. Use these to configure your app for tests.

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

¥For example, this could be used to setup App router in Vue.js:

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 中的类似配置如下所示:

¥A similar configuration in Next.js would look like this:

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 版本

¥Version 1.23

网络重播

¥Network Replay

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

¥Now you can record network traffic into a HAR file and re-use this traffic in your tests.

将网络记录到 HAR 文件中:

¥To record network into HAR file:

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

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

¥Alternatively, you can record HAR programmatically:

const context = await browser.newContext({
recordHar: { path: 'github.har.zip' }
});
// ... do stuff ...
await context.close();

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

¥Use the new methods page.routeFromHAR() or browserContext.routeFromHAR() to serve matching responses from the HAR file:

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

阅读 我们的文档 中的更多内容。

¥Read more in our documentation.

高级路由

¥Advanced Routing

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

¥You can now use route.fallback() to defer routing to other handlers.

考虑以下示例:

¥Consider the following example:

// Remove a header from all requests.
test.beforeEach(async ({ page }) => {
await page.route('**/*', async route => {
const headers = await route.request().allHeaders();
delete headers['if-none-match'];
await route.fallback({ headers });
});
});

test('should work', async ({ page }) => {
await page.route('**/*', async route => {
if (route.request().resourceType() === 'image')
await route.abort();
else
await route.fallback();
});
});

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

¥Note that the new methods page.routeFromHAR() and browserContext.routeFromHAR() also participate in routing and could be deferred to.

Web 优先断言更新

¥Web-First Assertions Update

组件测试更新

¥Component Tests Update

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

¥Read more about component testing with Playwright.

杂项

¥Miscellaneous

  • 如果有一个 Service Worker 挡住了你的路,你现在可以使用新的上下文选项 serviceWorkers 轻松禁用它:

    ¥If there's a service worker that's in your way, you can now easily disable it with a new context option serviceWorkers:

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

    ¥Using .zip path for recordHar context option automatically zips the resulting HAR:

    const context = await browser.newContext({
    recordHar: {
    path: 'github.har.zip',
    }
    });
  • 如果你打算手动编辑 HAR,请考虑使用 "minimal" HAR 记录模式,该模式仅记录重放所必需的信息:

    ¥If you intend to edit HAR by hand, consider using the "minimal" HAR recording mode that only records information that is essential for replaying:

    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

    ¥Playwright now runs on Ubuntu 22 amd64 and Ubuntu 22 arm64. We also publish new docker image mcr.microsoft.com/playwright:v1.34.0-jammy.

⚠️ 重大变化 ⚠️

¥⚠️ Breaking Changes ⚠️

如果对指定 url 的请求具有以下任何 HTTP 状态代码,则 WebServer 现在被视为 "ready":

¥WebServer is now considered "ready" if request to the specified url has any of the following HTTP status codes:

  • 200-299

  • 300-399(新的)

    ¥300-399 (new)

  • 400401402403(新)

    ¥400, 401, 402, 403 (new)

1.22 版本

¥Version 1.22

高亮

¥Highlights

  • 组件测试(预览)

    ¥Components Testing (preview)

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

    ¥Playwright Test can now test your React, Vue.js or Svelte components. You can use all the features of Playwright Test (such as parallelization, emulation & debugging) while running components in real browsers.

    典型的组件测试如下所示:

    ¥Here is what a typical component test looks like:

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

    阅读 我们的文档 中的更多内容。

    ¥Read more in our documentation.

  • 允许按 ARIA 角色ARIA 属性可访问的名称 选择元素的角色选择器。

    ¥Role selectors that allow selecting elements by their ARIA role, ARIA attributes and accessible name.

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

    阅读 我们的文档 中的更多内容。

    ¥Read more in our documentation.

  • 用于过滤现有定位器的新 locator.filter() API

    ¥New locator.filter() API to filter an existing locator

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

    ¥New web-first assertions expect(page).toHaveScreenshot() and expect(locator).toHaveScreenshot() that wait for screenshot stabilization and enhances test reliability.

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

    ¥The new assertions has screenshot-specific defaults, such as:

    • 禁用动画

      ¥disables animations

    • 使用 CSS 缩放选项

      ¥uses CSS scale option

    await page.goto('https://playwright.nodejs.cn');
    await expect(page).toHaveScreenshot();

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

    ¥The new expect(page).toHaveScreenshot() saves screenshots at the same location as expect(value).toMatchSnapshot().

1.21 版本

¥Version 1.21

高亮

¥Highlights

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

    ¥New role selectors that allow selecting elements by their ARIA role, ARIA attributes and accessible name.

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

    阅读 我们的文档 中的更多内容。

    ¥Read more in our documentation.

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

    ¥New scale option in page.screenshot() for smaller sized screenshots.

  • page.screenshot() 中的新 caret 选项用于控制文本插入符。默认为 "hide"

    ¥New caret option in page.screenshot() to control text caret. Defaults to "hide".

  • 用于等待任意条件的新方法 expect.poll

    ¥New method expect.poll to wait for an arbitrary condition:

    // 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() 等。在 我们的文档 中了解更多信息。

    ¥expect.poll supports most synchronous matchers, like .toBe(), .toContain(), etc. Read more in our documentation.

行为改变

¥Behavior Changes

  • 现在默认启用运行 TypeScript 测试时的 ESM 支持。不再需要 PLAYWRIGHT_EXPERIMENTAL_TS_ESM 环境变量。

    ¥ESM support when running TypeScript tests is now enabled by default. The PLAYWRIGHT_EXPERIMENTAL_TS_ESM env variable is no longer required.

  • mcr.microsoft.com/playwright docker 镜像不再包含 Python。请使用 mcr.microsoft.com/playwright/python 作为 Playwright-ready docker 镜像并预装 Python。

    ¥The mcr.microsoft.com/playwright docker image no longer contains Python. Please use mcr.microsoft.com/playwright/python as a Playwright-ready docker image with pre-installed Python.

  • Playwright 现在支持通过 locator.setInputFiles() API 上传大文件(数百 MB)。

    ¥Playwright now supports large file uploads (100s of MBs) via locator.setInputFiles() API.

浏览器版本

¥Browser Versions

  • Chromium 101.0.4951.26

  • 火狐浏览器 98.0.2

    ¥Mozilla Firefox 98.0.2

  • 网络工具包 15.4

    ¥WebKit 15.4

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

¥This version was also tested against the following stable channels:

  • 谷歌浏览器 100

    ¥Google Chrome 100

  • 微软 Edge 100

    ¥Microsoft Edge 100

1.20 版本

¥Version 1.20

高亮

¥Highlights

  • 方法 page.screenshot()locator.screenshot()elementHandle.screenshot() 的新选项:

    ¥New options for methods page.screenshot(), locator.screenshot() and elementHandle.screenshot():

    • 选项 animations: "disabled" 倒回所有 CSS 动画并转换到一致的状态

      ¥Option animations: "disabled" rewinds all CSS animations and transitions to a consistent state

    • 选项 mask: Locator[] 屏蔽给定元素,用粉红色 #FF00FF 框覆盖它们。

      ¥Option mask: Locator[] masks given elements, overlaying them with pink #FF00FF boxes.

  • expect().toMatchSnapshot() 现在支持匿名快照:当快照名称缺失时,Playwright Test 将自动生成一个:

    ¥expect().toMatchSnapshot() now supports anonymous snapshots: when snapshot name is missing, Playwright Test will generate one automatically:

    expect('Web is Awesome <3').toMatchSnapshot();
  • 新的 maxDiffPixelsmaxDiffPixelRatio 选项可使用 expect().toMatchSnapshot() 进行细粒度屏幕截图比较:

    ¥New maxDiffPixels and maxDiffPixelRatio options for fine-grained screenshot comparison using expect().toMatchSnapshot():

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

    testConfig.expect 中指定一次 maxDiffPixelsmaxDiffPixelRatio 是最方便的。

    ¥It is most convenient to specify maxDiffPixels or maxDiffPixelRatio once in testConfig.expect.

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

    ¥Playwright Test now adds testConfig.fullyParallel mode. By default, Playwright Test parallelizes between files. In fully parallel mode, tests inside a single file are also run in parallel. You can also use --fully-parallel command line flag.

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

    ¥testProject.grep and testProject.grepInvert are now configurable per project. For example, you can now configure smoke tests project using grep:

    playwright.config.ts
    export default {
    projects: [
    {
    name: 'smoke tests',
    grep: /@smoke/,
    },
    ],
    };
  • 跟踪查看器 现在显示 API 测试请求

    ¥Trace Viewer now shows API testing requests.

  • locator.highlight() 直观地显示元素以便于调试。

    ¥locator.highlight() visually reveals element(s) for easier debugging.

公告

¥Announcements

  • 我们现在发布指定的 Python docker 镜像 mcr.microsoft.com/playwright/python。如果你使用 Python,请切换到它。这是在我们的 javascript mcr.microsoft.com/playwright docker 镜像中包含 Python 的最后一个版本。

    ¥We now ship a designated Python docker image mcr.microsoft.com/playwright/python. Please switch over to it if you use Python. This is the last release that includes Python inside our javascript mcr.microsoft.com/playwright docker image.

  • v1.20 是接收 macOS 10.15 Catalina WebKit 更新的最后一个版本。请更新 MacOS 以继续使用最新、最好的 WebKit!

    ¥v1.20 is the last release to receive WebKit update for macOS 10.15 Catalina. Please update MacOS to keep using latest & greatest WebKit!

浏览器版本

¥Browser Versions

  • Chromium 101.0.4921.0

  • 火狐浏览器 97.0.1

    ¥Mozilla Firefox 97.0.1

  • 网络工具包 15.4

    ¥WebKit 15.4

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

¥This version was also tested against the following stable channels:

  • 谷歌浏览器 99

    ¥Google Chrome 99

  • 微软 Edge 99

    ¥Microsoft Edge 99

1.19 版本

¥Version 1.19

Playwright 测试更新

¥Playwright Test Update

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

    ¥Playwright Test v1.19 now supports soft assertions. Failed soft assertions

    不终止测试执行,而是将测试标记为失败。

    ¥do not terminate test execution, but mark the test as failed.

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

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

    ¥Read more in our documentation

  • 你现在可以指定自定义期望消息作为 expectexpect.soft 函数的第二个参数,例如:

    ¥You can now specify a custom expect message as a second argument to the expect and expect.soft functions, for example:

    await expect(page.locator('text=Name'), 'should be logged in').toBeVisible();

    错误看起来像这样:

    ¥The error would look like this:

        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 |

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

    ¥Read more in our documentation

  • 默认情况下,单个文件中的测试按顺序运行。如果单个文件中有许多独立测试,你现在可以与 test.describe.configure() 并行运行它们。

    ¥By default, tests in a single file are run in order. If you have many independent tests in a single file, you can now run them in parallel with test.describe.configure().

其他更新

¥Other Updates

Playwright 测试全局设置可能发生重大变化

¥Potentially breaking change in Playwright Test Global Setup

此更改不太可能影响你,如果你的测试继续按原样运行,则无需采取任何操作。

¥It is unlikely that this change will affect you, no action is required if your tests keep running as they did.

我们注意到,在极少数情况下,要执行的测试集是通过环境变量在全局设置中配置的。我们还注意到一些应用在全局拆解中对报告器的输出进行后处理。如果你正在执行两者之一,了解更多

¥We've noticed that in rare cases, the set of tests to be executed was configured in the global setup by means of the environment variables. We also noticed some applications that were post processing the reporters' output in the global teardown. If you are doing one of the two, learn more

浏览器版本

¥Browser Versions

  • Chromium 100.0.4863.0

  • 火狐浏览器 96.0.1

    ¥Mozilla Firefox 96.0.1

  • 网络工具包 15.4

    ¥WebKit 15.4

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

¥This version was also tested against the following stable channels:

  • 谷歌浏览器 98

    ¥Google Chrome 98

  • 微软 Edge 98

    ¥Microsoft Edge 98

1.18 版本

¥Version 1.18

定位器改进

¥Locator Improvements

测试 API 改进

¥Testing API improvements

改进的 TypeScript 支持

¥Improved TypeScript Support

  1. Playwright Test 现在尊重 tsconfig.jsonbaseUrlpaths,因此你可以使用别名

    ¥Playwright Test now respects tsconfig.json's baseUrl and paths, so you can use aliases

  2. 有一个新的环境变量 PW_EXPERIMENTAL_TS_ESM,允许在 TS 代码中导入 ESM 模块,而无需编译步骤。导入 esm 模块时,不要忘记 .js 后缀。按如下方式运行测试:

    ¥There is a new environment variable PW_EXPERIMENTAL_TS_ESM that allows importing ESM modules in your TS code, without the need for the compile step. Don't forget the .js suffix when you are importing your esm modules. Run your tests as follows:

npm i --save-dev @playwright/test@1.18.0-rc1
PW_EXPERIMENTAL_TS_ESM=1 npx playwright test

创建 Playwright

¥Create Playwright

npm init playwright 命令现在可供你普遍使用:

¥The npm init playwright command is now generally available for your use:

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

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

¥This will create a Playwright Test configuration file, optionally add examples, a GitHub Action workflow and a first test example.spec.ts.

新的 API 和更改

¥New APIs & changes

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

¥Breaking change: custom config options

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

¥Custom config options are a convenient way to parametrize projects with different values. Learn more in this guide.

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

¥Previously, any fixture introduced through test.extend() could be overridden in the testProject.use config section. For example,

// WRONG: THIS SNIPPET DOES NOT WORK SINCE v1.18.

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

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

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

¥The proper way to make a fixture parametrized in the config file is to specify option: true when defining the fixture. For example,

// CORRECT: THIS SNIPPET WORKS SINCE v1.18.

// fixtures.js
const test = base.extend({
// Fixtures marked as "option: true" will get a value specified in the config,
// or fallback to the default value.
myParameter: ['default', { option: true }],
});

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

浏览器版本

¥Browser Versions

  • Chromium 99.0.4812.0

  • 火狐浏览器 95.0

    ¥Mozilla Firefox 95.0

  • 网络工具包 15.4

    ¥WebKit 15.4

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

¥This version was also tested against the following stable channels:

  • 谷歌浏览器 97

    ¥Google Chrome 97

  • 微软 Edge 97

    ¥Microsoft Edge 97

1.17 版本

¥Version 1.17

框架定位器

¥Frame Locators

Playwright 1.17 引入 帧定位器 - 页面上 iframe 的定位器。帧定位器捕获足以检索 iframe 的逻辑,然后定位该 iframe 中的元素。默认情况下,帧定位器是严格的,将等待 iframe 出现,并且可以在 Web 优先断言中使用。

¥Playwright 1.17 introduces frame locators - a locator to the iframe on the page. Frame locators capture the logic sufficient to retrieve the iframe and then locate elements in that iframe. Frame locators are strict by default, will wait for iframe to appear and can be used in Web-First assertions.

Graphics

帧定位器可以使用 page.frameLocator()locator.frameLocator() 方法创建。

¥Frame locators can be created with either page.frameLocator() or locator.frameLocator() method.

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

欲了解更多内容,请访问 我们的文档

¥Read more at our documentation.

跟踪查看器更新

¥Trace Viewer Update

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

¥Playwright Trace Viewer is now available online at https://trace.playwright.dev! Just drag-and-drop your trace.zip file to inspect its contents.

注意:跟踪文件没有上传到任何地方;trace.playwright.dev 是本地处理跟踪的 渐进式网络应用

¥NOTE: trace files are not uploaded anywhere; trace.playwright.dev is a progressive web application that processes traces locally.

  • Playwright 测试跟踪现在默认包括源(可以使用跟踪选项关闭这些源)

    ¥Playwright Test traces now include sources by default (these could be turned off with tracing option)

  • 跟踪查看器现在显示测试名称

    ¥Trace Viewer now shows test name

  • 包含浏览器详细信息的新跟踪元数据选项卡

    ¥New trace metadata tab with browser details

  • 快照现在有 URL 栏

    ¥Snapshots now have URL bar

image

HTML 报告更新

¥HTML Report Update

  • HTML 报告现在支持动态过滤

    ¥HTML report now supports dynamic filtering

  • 报告现在是一个静态 HTML 文件,可以通过电子邮件或作为 Slack 附件发送。

    ¥Report is now a single static HTML file that could be sent by e-mail or as a slack attachment.

image

Ubuntu ARM64 支持及更多

¥Ubuntu ARM64 support + more

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

    ¥Playwright now supports Ubuntu 20.04 ARM64. You can now run Playwright tests inside Docker on Apple M1 and on Raspberry Pi.

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

    ¥You can now use Playwright to install stable version of Edge on Linux:

    npx playwright install msedge

新 API

¥New APIs

1.16 版本

¥Version 1.16

🎭 Playwright 测试

¥🎭 Playwright Test

API 测试

¥API Testing

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

¥Playwright 1.16 introduces new API Testing that lets you send requests to the server directly from Node.js! Now you can:

  • 测试你的服务器 API

    ¥test your server API

  • 在测试中访问 Web 应用之前准备服务器端状态

    ¥prepare server side state before visiting the web application in a test

  • 在浏览器中运行某些操作后验证服务器端后置条件

    ¥validate server side post-conditions after running some actions in the browser

要代表 Playwright 页面触发请求,请使用新的 page.request API:

¥To do a request on behalf of Playwright's Page, use new page.request API:

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

test('context fetch', async ({ page }) => {
// Do a GET request on behalf of page
const response = await page.request.get('http://example.com/foo.json');
// ...
});

要从 node.js 向 API 端点触发独立请求,请使用 new request 夹具

¥To do a stand-alone request from node.js to an API endpoint, use new request fixture:

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

test('context fetch', async ({ request }) => {
// Do a GET request on behalf of page
const response = await request.get('http://example.com/foo.json');
// ...
});

在我们的 API 测试指南 中了解更多相关信息。

¥Read more about it in our API testing guide.

响应拦截

¥Response Interception

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

¥It is now possible to do response interception by combining API Testing with request interception.

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

¥For example, we can blur all the images on the page:

import { test, expect } from '@playwright/test';
import jimp from 'jimp'; // image processing library

test('response interception', async ({ page }) => {
await page.route('**/*.jpeg', async route => {
const response = await page._request.fetch(route.request());
const image = await jimp.read(await response.body());
await image.blur(5);
await route.fulfill({
response,
body: await image.getBufferAsync('image/jpeg'),
});
});
const response = await page.goto('https://playwright.nodejs.cn');
expect(response.status()).toBe(200);
});

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

¥Read more about response interception.

新的 HTML 报告器

¥New HTML reporter

playwright.config.ts 文件中使用 --reporter=htmlreporter 条目尝试新的 HTML 报告器:

¥Try it out new HTML reporter with either --reporter=html or a reporter entry in playwright.config.ts file:

$ npx playwright test --reporter=html

HTML 报告器拥有有关测试及其失败的所有信息,包括表面痕迹和图片伪影。

¥The HTML reporter has all the information about tests and their failures, including surfacing trace and image artifacts.

html reporter

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

¥Read more about our reporters.

🎭 Playwright 库

¥🎭 Playwright Library

locator.waitFor

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

¥Wait for a locator to resolve to a single element with a given state. Defaults to the state: 'visible'.

使用列表时特别方便:

¥Comes especially handy when working with lists:

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

test('context fetch', async ({ page }) => {
const completeness = page.locator('text=Success');
await completeness.waitFor();
expect(await page.screenshot()).toMatchSnapshot('screen.png');
});

了解有关 locator.waitFor() 的更多信息。

¥Read more about locator.waitFor().

Docker 对 Arm64 的支持

¥Docker support for Arm64

Playwright Docker 镜像现已发布适用于 Arm64 的版本,因此可以在 Apple Silicon 上使用。

¥Playwright Docker image is now published for Arm64 so it can be used on Apple Silicon.

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

¥Read more about Docker integration.

🎭 Playwright 踪迹查看器

¥🎭 Playwright Trace Viewer

  • 跟踪查看器中的 Web 优先断言

    ¥web-first assertions inside trace viewer

  • 使用 npx playwright show-trace 运行跟踪查看器并将跟踪文件拖放到跟踪查看器 PWA

    ¥run trace viewer with npx playwright show-trace and drop trace files to the trace viewer PWA

  • API 测试与跟踪查看器集成

    ¥API testing is integrated with trace viewer

  • 更好地对行动目标进行视觉归因

    ¥better visual attribution of action targets

了解有关 跟踪查看器 的更多信息。

¥Read more about Trace Viewer.

浏览器版本

¥Browser Versions

  • Chromium 97.0.4666.0

  • 火狐浏览器 93.0

    ¥Mozilla Firefox 93.0

  • 网络工具包 15.4

    ¥WebKit 15.4

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

¥This version of Playwright was also tested against the following stable channels:

  • 谷歌浏览器 94

    ¥Google Chrome 94

  • 微软 Edge 94

    ¥Microsoft Edge 94

1.15 版本

¥Version 1.15

🎭 Playwright 库

¥🎭 Playwright Library

🖱️ 鼠标滚轮

¥🖱️ Mouse Wheel

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

¥By using mouse.wheel() you are now able to scroll vertically or horizontally.

📜 新的标头 API

¥📜 New Headers API

以前不可能获取响应的多个标头值。现在这是可能的,并且可以使用其他辅助函数:

¥Previously it was not possible to get multiple header values of a response. This is now possible and additional helper functions are available:

🌈 强制颜色模拟

¥🌈 Forced-Colors emulation

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

¥Its now possible to emulate the forced-colors CSS media feature by passing it in the browser.newContext() or calling page.emulateMedia().

新 API

¥New APIs

🎭 Playwright 测试

¥🎭 Playwright Test

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

¥🤝 test.parallel() run tests in the same file in parallel

test.describe.parallel('group', () => {
test('runs in parallel 1', async ({ page }) => {
});
test('runs in parallel 2', async ({ page }) => {
});
});

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

¥By default, tests in a single file are run in order. If you have many independent tests in a single file, you can now run them in parallel with test.describe.parallel(title, callback).

🛠 添加 --debug CLI 标志

¥🛠 Add --debug CLI flag

通过使用 npx playwright test --debug,你可以使用 Playwright 检查器 来调试测试。

¥By using npx playwright test --debug it will enable the Playwright Inspector for you to debug your tests.

浏览器版本

¥Browser Versions

  • Chromium 96.0.4641.0

  • 火狐浏览器 92.0

    ¥Mozilla Firefox 92.0

  • 网络工具包 15.0

    ¥WebKit 15.0

1.14 版本

¥Version 1.14

🎭 Playwright 库

¥🎭 Playwright Library

⚡ 新 "strict" 模式

¥⚡️ New "strict" mode

选择器歧义是自动化测试中的一个常见问题。"strict" 模式确保你的选择器指向单个元素,否则抛出异常。

¥Selector ambiguity is a common problem in automation testing. "strict" mode ensures that your selector points to a single element and throws otherwise.

strict: true 传递到你的操作调用中以选择加入。

¥Pass strict: true into your action calls to opt in.

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

📍 新 定位器 API

¥📍 New Locators API

定位器表示页面上元素的视图。它捕获足以在任何给定时刻检索元素的逻辑。

¥Locator represents a view to the element(s) on the page. It captures the logic sufficient to retrieve the element at any given moment.

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

¥The difference between the Locator and ElementHandle is that the latter points to a particular element, while Locator captures the logic of how to retrieve that element.

另外,定位器默认为 "strict"!

¥Also, locators are "strict" by default!

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

documentation 中了解更多信息。

¥Learn more in the documentation.

🧩 实验性 ReactVue 选择器引擎

¥🧩 Experimental React and Vue selector engines

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

¥React and Vue selectors allow selecting elements by its component name and/or property values. The syntax is very similar to attribute selectors and supports all attribute selector operators.

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

反应选择器文档vue 选择器文档 中了解更多信息。

¥Learn more in the react selectors documentation and the vue selectors documentation.

✨ 新的 nthvisible 选择器引擎

¥✨ New nth and visible selector engines

  • nth 选择器引擎相当于 :nth-match 伪类,但可以与其他选择器引擎组合。

    ¥nth selector engine is equivalent to the :nth-match pseudo class, but could be combined with other selector engines.

  • visible 选择器引擎相当于 :visible 伪类,但可以与其他选择器引擎组合。

    ¥visible selector engine is equivalent to the :visible pseudo class, but could be combined with other selector engines.

// select the first button among all buttons
await button.click('button >> nth=0');
// or if you are using locators, you can use first(), nth() and last()
await page.locator('button').first().click();

// click a visible button
await button.click('button >> visible=true');

🎭 Playwright 测试

¥🎭 Playwright Test

✅ Web 优先断言

¥✅ Web-First Assertions

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

¥expect now supports lots of new web-first assertions.

考虑以下示例:

¥Consider the following example:

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

Playwright Test 将使用选择器 .status 重新测试节点,直到获取的节点具有 "Submitted" 文本。它将重新获取节点并一遍又一遍地检查它,直到满足条件或达到超时。你可以通过此超时或通过测试配置中的 testProject.expect 值配置一次。

¥Playwright Test will be re-testing the node with the selector .status until fetched Node has the "Submitted" text. It will be re-fetching the node and checking it over and over, until the condition is met or until the timeout is reached. You can either pass this timeout or configure it once via the testProject.expect value in test config.

默认情况下,未设置断言超时,因此它将永远等待,直到整个测试超时。

¥By default, the timeout for assertions is not set, so it'll wait forever, until the whole test times out.

所有新断言列表:

¥List of all new assertions:

⛓ 使用 describe.serial 的串行模式

¥⛓ Serial mode with describe.serial

声明一组应始终串行运行的测试。如果其中一项测试失败,则跳过所有后续测试。一组中的所有测试都会一起重试。

¥Declares a group of tests that should always be run serially. If one of the tests fails, all subsequent tests are skipped. All tests in a group are retried together.

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

documentation 中了解更多信息。

¥Learn more in the documentation.

🐾 使用 test.step 的步骤 API

¥🐾 Steps API with test.step

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

¥Split long tests into multiple steps using test.step() API:

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

test('test', async ({ page }) => {
await test.step('Log in', async () => {
// ...
});
await test.step('news feed', async () => {
// ...
});
});

步骤信息在报告器 API 中公开。

¥Step information is exposed in reporters API.

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

¥🌎 Launch web server before running tests

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

¥To launch a server during the tests, use the webServer option in the configuration file. The server will wait for a given url to be available before running the tests, and the url will be passed over to Playwright as a baseURL when creating a context.

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,
},
});

documentation 中了解更多信息。

¥Learn more in the documentation.

浏览器版本

¥Browser Versions

  • Chromium 94.0.4595.0

  • 火狐浏览器 91.0

    ¥Mozilla Firefox 91.0

  • 网络工具包 15.0

    ¥WebKit 15.0

1.13 版本

¥Version 1.13

Playwright 测试

¥Playwright Test

Playwright

工具

¥Tools

  • Playwright Trace Viewer 现在显示参数、返回值和 console.log() 调用。

    ¥Playwright Trace Viewer now shows parameters, returned values and console.log() calls.

  • Playwright Inspector 可以生成 Playwright Test 测试。

    ¥Playwright Inspector can generate Playwright Test tests.

新的和大修的指南

¥New and Overhauled Guides

浏览器版本

¥Browser Versions

  • Chromium 93.0.4576.0

  • 火狐浏览器 90.0

    ¥Mozilla Firefox 90.0

  • 网络工具包 14.2

    ¥WebKit 14.2

新 Playwright API

¥New Playwright APIs

1.12 版本

¥Version 1.12

⚡ Playwright 测试简介

¥⚡️ Introducing Playwright Test

Playwright 测试 是 Playwright 团队从头开始构建的新测试运行器,专门用于满足端到端测试需求:

¥Playwright Test is a new test runner built from scratch by Playwright team specifically to accommodate end-to-end testing needs:

  • 在所有浏览器上运行测试。

    ¥Run tests across all browsers.

  • 并行执行测试。

    ¥Execute tests in parallel.

  • 享受开箱即用的上下文隔离和合理的默认设置。

    ¥Enjoy context isolation and sensible defaults out of the box.

  • 捕获失败时的视频、屏幕截图和其他工件。

    ¥Capture videos, screenshots and other artifacts on failure.

  • 将 POM 集成为可扩展的装置。

    ¥Integrate your POMs as extensible fixtures.

安装:

¥Installation:

npm i -D @playwright/test

简单测试 tests/foo.spec.ts

¥Simple test tests/foo.spec.ts:

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

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

运行:

¥Running:

npx playwright test

👉 阅读 Playwright 测试文档 中的更多内容。

¥👉 Read more in Playwright Test documentation.

🧟‍♂️ Playwright 跟踪查看器简介

¥🧟‍♂️ Introducing Playwright Trace Viewer

Playwright 踪迹查看器 是一个新的 GUI 工具,可帮助探索脚本运行后记录的 Playwright 痕迹。Playwright 的踪迹让你可以检查:

¥Playwright Trace Viewer is a new GUI tool that helps exploring recorded Playwright traces after the script ran. Playwright traces let you examine:

  • 每个 Playwright 操作之前和之后的页面 DOM

    ¥page DOM before and after each Playwright action

  • 每个 Playwright 操作之前和之后的页面渲染

    ¥page rendering before and after each Playwright action

  • 脚本执行期间的浏览器网络

    ¥browser network during script execution

使用新的 browserContext.tracing API 记录跟踪:

¥Traces are recorded using the new browserContext.tracing API:

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

// Start tracing before creating / navigating a page.
await context.tracing.start({ screenshots: true, snapshots: true });

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

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

稍后使用 Playwright CLI 检查痕迹:

¥Traces are examined later with the Playwright CLI:

npx playwright show-trace trace.zip

这将打开以下 GUI:

¥That will open the following GUI:

image

👉 阅读 跟踪查看器文档 中的更多内容。

¥👉 Read more in trace viewer documentation.

浏览器版本

¥Browser Versions

  • Chromium 93.0.4530.0

  • 火狐浏览器 89.0

    ¥Mozilla Firefox 89.0

  • 网络工具包 14.2

    ¥WebKit 14.2

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

¥This version of Playwright was also tested against the following stable channels:

  • 谷歌浏览器 91

    ¥Google Chrome 91

  • 微软 Edge 91

    ¥Microsoft Edge 91

新 API

¥New APIs

1.11 版本

¥Version 1.11

🎥 新视频:Playwright:现代 Web 的新测试自动化框架(slides)

¥🎥 New video: Playwright: A New Test Automation Framework for the Modern Web (slides)

  • 我们谈论了 Playwright

    ¥We talked about Playwright

  • 展示了幕后的工程工作

    ¥Showed engineering work behind the scenes

  • 进行了新功能的现场演示 ✨

    ¥Did live demos with new features ✨

  • 特别感谢 applitools 主办这次活动并邀请我们!

    ¥Special thanks to applitools for hosting the event and inviting us!

浏览器版本

¥Browser Versions

  • Chromium 92.0.4498.0

  • 火狐浏览器 89.0b6

    ¥Mozilla Firefox 89.0b6

  • 网络工具包 14.2

    ¥WebKit 14.2

新 API

¥New APIs

1.10 版本

¥Version 1.10

打包的浏览器版本

¥Bundled Browser Versions

  • Chromium 90.0.4430.0

  • 火狐浏览器 87.0b10

    ¥Mozilla Firefox 87.0b10

  • 网络工具包 14.2

    ¥WebKit 14.2

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

¥This version of Playwright was also tested against the following stable channels:

  • 谷歌浏览器 89

    ¥Google Chrome 89

  • 微软 Edge 89

    ¥Microsoft Edge 89

新 API

¥New APIs

1.9 版本

¥Version 1.9

  • Playwright 检查器 是一个新的 GUI 工具,用于编写和调试测试。

    ¥Playwright Inspector is a new GUI tool to author and debug your tests.

    • 对 Playwright 脚本进行逐行调试,包括播放、暂停和单步执行。

      ¥Line-by-line debugging of your Playwright scripts, with play, pause and step-through.

    • 通过记录用户操作来编写新脚本。

      ¥Author new scripts by recording user actions.

    • 通过将鼠标悬停在元素上来为脚本生成元素选择器。

      ¥Generate element selectors for your script by hovering over elements.

    • 设置 PWDEBUG=1 环境变量以启动 Inspector

      ¥Set the PWDEBUG=1 environment variable to launch the Inspector

  • 在标题模式下使用 page.pause() 暂停脚本执行。暂停页面会启动 Playwright 检查器 进行调试。

    ¥Pause script execution with page.pause() in headed mode. Pausing the page launches Playwright Inspector for debugging.

  • CSS 选择器的新 has-text 伪类。:has-text("example") 匹配内部某处包含 "example" 的任何元素,可能在子元素或后代元素中。参见 更多例子

    ¥New has-text pseudo-class for CSS selectors. :has-text("example") matches any element containing "example" somewhere inside, possibly in a child or a descendant element. See more examples.

  • 除非配置了 dialog 事件的监听器,否则页面对话框现在会在执行期间自动关闭。了解更多 关于这个。

    ¥Page dialogs are now auto-dismissed during execution, unless a listener for dialog event is configured. Learn more about this.

  • Python Playwright 现已稳定,具有惯用的蛇形案例 API 和预构建的 Docker 镜像 以在 CI/CD 中运行测试。

    ¥Playwright for Python is now stable with an idiomatic snake case API and pre-built Docker image to run tests in CI/CD.

浏览器版本

¥Browser Versions

  • Chromium 90.0.4421.0

  • 火狐浏览器 86.0b10

    ¥Mozilla Firefox 86.0b10

  • 网络工具包 14.1

    ¥WebKit 14.1

新 API

¥New APIs

1.8 版本

¥Version 1.8

新 API

¥New APIs

浏览器版本

¥Browser Versions

  • Chromium 90.0.4392.0

  • 火狐浏览器 85.0b5

    ¥Mozilla Firefox 85.0b5

  • 网络工具包 14.1

    ¥WebKit 14.1

1.7 版本

¥Version 1.7

  • 新的 Java SDK:Java Playwright 现在与 JavaScriptPython.NET 绑定 同等。

    ¥New Java SDK: Playwright for Java is now on par with JavaScript, Python and .NET bindings.

  • 浏览器存储 API:新的便利 API 用于保存和加载浏览器存储状态(cookie、本地存储),以通过身份验证简化自动化场景。

    ¥Browser storage API: New convenience APIs to save and load browser storage state (cookies, local storage) to simplify automation scenarios with authentication.

  • 新的 CSS 选择器:我们听取了你对更灵活的选择器的反馈,并改进了选择器的实现。Playwright 1.7 引入了 新的 CSS 扩展,并且即将推出更多内容。

    ¥New CSS selectors: We heard your feedback for more flexible selectors and have revamped the selectors implementation. Playwright 1.7 introduces new CSS extensions and there's more coming soon.

  • 新网站:playwright.dev 的文档网站已更新,现在使用 Docusaurus 构建。

    ¥New website: The docs website at playwright.dev has been updated and is now built with Docusaurus.

  • 对苹果芯片的支持:适用于 WebKit 和 Chromium 的 Playwright 浏览器二进制文件现已针对 Apple Silicon 构建。

    ¥Support for Apple Silicon: Playwright browser binaries for WebKit and Chromium are now built for Apple Silicon.

新 API

¥New APIs

浏览器版本

¥Browser Versions

  • Chromium 89.0.4344.0

  • 火狐浏览器 84.0b9

    ¥Mozilla Firefox 84.0b9

  • 网络工具包 14.1

    ¥WebKit 14.1