跳至主要内容

发布说明

版本 1.51

用于indexedDB的StorageState

  • New option indexedDB for browserContext.storageState() allows to save and restore IndexedDB contents. Useful when your application uses IndexedDB API to store authentication tokens, like Firebase Authentication.

    Here is an example following the authentication guide:

    tests/auth.setup.ts
    import { test as setup, expect } from '@playwright/test';
    import path from 'path';

    const authFile = path.join(__dirname, '../playwright/.auth/user.json');

    setup('authenticate', async ({ page }) => {
    await page.goto('/');
    // ... perform authentication steps ...

    // make sure to save indexedDB
    await page.context().storageState({ path: authFile, indexedDB: true });
    });

复制为提示

New "Copy prompt" button on errors in the HTML report, trace viewer and UI mode. Click to copy a pre-filled LLM prompt that contains the error message and useful context for fixing the error.

Copy prompt

筛选可见元素

新选项 visible 用于 locator.filter() 允许仅匹配可见元素。

example.spec.ts
test('some test', async ({ page }) => {
// Ignore invisible todo items.
const todoItems = page.getByTestId('todo-item').filter({ visible: true });
// Check there are exactly 3 visible ones.
await expect(todoItems).toHaveCount(3);
});

Git information in HTML report

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

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

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

HTML report will show this information when available:

Git information in the report

测试步骤改进

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

test('some test', async ({ page, isMobile }) => {
// Note the new "step" argument:
await test.step('here is my step', async step => {
step.skip(isMobile, 'not relevant on mobile layouts');

// ...
await step.attach('my attachment', { body: 'some text' });
// ...
});
});

其他

浏览器版本

  • Chromium 134.0.6998.35
  • Mozilla Firefox 135.0
  • WebKit 18.4

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

  • Google Chrome 133
  • Microsoft Edge 133

版本 1.50

测试运行器

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

    test('some test', async ({ page }) => {
    await test.step('a step', async () => {
    // 该步骤可以独立于测试单独设置超时
    }, { timeout: 1000 });
    });
  • New method test.step.skip() to disable execution of a test step.

    test('some test', async ({ page }) => {
    await test.step('before running step', async () => {
    // Normal step
    });

    await test.step.skip('not yet ready', async () => {
    // This step is skipped
    });

    await test.step('after running step', async () => {
    // This step still runs even though the previous one was skipped
    });
    });
  • 扩展了expect(locator).toMatchAriaSnapshot()功能,允许将aria快照存储在单独的YAML文件中。

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

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

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

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

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

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

用户界面更新

  • Updated default HTML reporter to improve display of attachments.
  • Codegen 中新增按钮,用于选择元素以生成 aria 快照。
  • 在追踪记录中,现在会显示更多详细信息(例如按下的按键)与操作API调用一起展示。
  • 在追踪记录中显示canvas内容容易出错。现在默认禁用此显示功能,可以通过Display canvas content界面设置来启用。
  • 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.dev');
await expect(page.locator('body')).toMatchAriaSnapshot(`
- banner:
- heading /Playwright enables reliable/ [level=1]
- link "Get started"
- link "Star microsoft/playwright on GitHub"
- main:
- img "Browsers (Chromium, Firefox, WebKit)"
- heading "Any browser • Any platform • One API"
`);

您可以使用Test Generator生成此断言,并通过--update-snapshots命令行标志更新预期的快照。

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

测试运行器

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

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

  • chrome, chrome-dev, chrome-beta, 或 chrome-canary
  • msedge, msedge-dev, msedge-beta, 或 msedge-canary

我需要做什么?

升级到Playwright v1.49后,运行您的测试套件。如果测试仍然通过,说明一切正常。如果未通过,您可能需要更新快照,并调整一些关于PDF查看器和扩展的测试代码。详情请参阅issue #33566

其他重大变更

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

尝试新的Chromium无头模式

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

另一方面,New Headless是真正的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

用户界面更新

  • New "copy" buttons for annotations and test location in the HTML report.
  • 路由方法调用如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模式和跟踪查看器中的Network选项卡有几项不错的改进:

  • 按资产类型和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 用于等待正在进行的监听器完成。
  • 现在可以通过将clientCertificates.certclientCertificates.key作为缓冲区而非文件路径传递,从内存中传递TLS客户端证书。
  • Attachments with a text/html content type can now be opened in a new tab in the HTML report. This is useful for including third-party reports or other HTML content in the Playwright test report and distributing it to your team.
  • noWaitAfter 选项在 locator.selectOption() 中已被弃用。
  • 我们收到关于Webkit中WebGL在GitHub Actions macos-13上运行异常的反馈。建议将GitHub Actions升级至macos-14

浏览器版本

  • Chromium 129.0.6668.29
  • Mozilla Firefox 130.0
  • WebKit 18.0

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

  • Google Chrome 128
  • Microsoft Edge 128

版本 1.46

TLS客户端证书

Playwright 现在允许您提供客户端证书,以便服务器可以根据 TLS 客户端认证规范进行验证。

以下代码片段为https://example.com设置了一个客户端证书:

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

export default defineConfig({
// ...
use: {
clientCertificates: [{
origin: 'https://example.com',
certPath: './cert.pem',
keyPath: './key.pem',
passphrase: 'mysecretpassword',
}],
},
// ...
});

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

--only-changed 命令行选项

新增CLI选项--only-changed将仅运行自上次git提交或特定git"ref"以来发生更改的测试文件。该选项还会运行所有引用了任何已更改文件的测试文件。

# 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 测试夹具

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

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

此夹具仅在组件测试中可用。

UI模式 / 追踪查看器更新

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

其他

浏览器版本

  • Chromium 128.0.6613.18
  • Mozilla Firefox 128.0
  • WebKit 18.0

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

  • Google Chrome 127
  • Microsoft Edge 127

版本 1.45

时钟

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

  • 使用预定义时间进行测试;
  • 保持时间与计时器的一致性;
  • 监控不活动状态;
  • 手动逐步推进时间。
// Initialize clock and let the page load naturally.
await page.clock.install({ time: new Date('2024-02-02T08:00:00') });
await page.goto('http://localhost:3333');

// Pretend that the user closed the laptop lid and opened it again at 10am,
// Pause the time once reached that point.
await page.clock.pauseAt(new Date('2024-02-02T10:00:00'));

// Assert the page state.
await expect(page.getByTestId('current-time')).toHaveText('2/2/2024, 10:00:00 AM');

// Close the laptop lid again and open it at 10:30am.
await page.clock.fastForward('30:00');
await expect(page.getByTestId('current-time')).toHaveText('2/2/2024, 10:30:00 AM');

更多详情请参阅时钟指南

测试运行器

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

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

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

    # 启用TTY特性,假设终端宽度为80
    PLAYWRIGHT_FORCE_TTY=80 npx playwright test
  • 新增选项 testConfig.respectGitIgnoretestProject.respectGitIgnore 用于控制在搜索测试时是否排除匹配 .gitignore 模式的文件。

  • New property timeout is now available for custom expect matchers. This property takes into account playwright.config.ts and expect.configure().

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

    export const expect = baseExpect.extend({
    async toHaveAmount(locator: Locator, expected: number, options?: { timeout?: number }) {
    // When no timeout option is specified, use the config timeout.
    const timeout = options?.timeout ?? this.timeout;
    // ... implement the assertion ...
    },
    });

其他

  • 方法 locator.setInputFiles() 现在支持为 元素上传整个目录。

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

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

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

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

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

定位器处理器

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 option in apiRequestContext.fetch() now accepts FormData and supports repeating fields with the same name.

    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
    });
  • 现在可以通过在testConfig.expect中全局配置或在testProject.expect中按项目配置expect.toPass.intervals选项来设置expect(callback).toPass({ intervals })

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

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

Reporter API

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

命令行

  • --last-failed CLI option to for running only tests that failed in the previous run.

    First run all tests:

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

    Now fix the failing tests and run Playwright again with --last-failed option:

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

    // 清除所有cookie
    await context.clearCookies();
    // 新增:清除特定名称的cookie
    await context.clearCookies({ name: 'session-id' });
    // 新增:清除特定域名的cookie
    await context.clearCookies({ domain: 'my-origin.com' });
  • testOptions.trace 的新模式 retain-on-first-failure。在此模式下,会记录每个测试首次运行的追踪信息,但不会记录重试时的信息。当测试运行失败时,追踪文件会被保留,否则将被删除。

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

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

    test('example', async ({ page }) => {
    console.log(test.info().tags);
    });
  • 新增方法 locator.contentFrame() 可将 Locator 对象转换为 FrameLocator。当您从某处获取到 Locator 对象后,若后续需要与框架内的内容进行交互,这个方法会非常有用。

    const locator = page.locator('iframe[name="embedded"]');
    // ...
    const frameLocator = locator.contentFrame();
    await frameLocator.getByRole('button').click();
  • 新增方法 frameLocator.owner() 可将 FrameLocator 对象转换为 Locator。当您从某处获取到 FrameLocator 对象后,若需要与 iframe 元素进行交互,这个方法会很有用。

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

UI模式更新

Playwright UI Mode

  • 在测试列表中查看标签。
  • 通过输入@fast或点击标签本身来按标签筛选。
  • New shortcuts:
    • 按"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 命令行 flag 现在支持 '*' 通配符:
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.dev/docs/test-annotations#tag-tests' },
],
}, async ({ page }) => {
// ...
});

公告

  • ⚠️ 不再支持Ubuntu 18系统。

浏览器版本

  • Chromium 123.0.6312.4
  • Mozilla Firefox 123.0
  • WebKit 17.4

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

  • Google Chrome 122
  • Microsoft Edge 123

版本 1.41

新API

浏览器版本

  • Chromium 121.0.6167.57
  • Mozilla Firefox 121.0
  • WebKit 17.4

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

  • Google Chrome 120
  • Microsoft Edge 120

版本 1.40

测试生成器更新

Playwright Test Generator

生成断言的新工具:

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

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

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

新API

其他变更

浏览器版本

  • Chromium 120.0.6099.28
  • Mozilla Firefox 119.0
  • WebKit 17.4

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

  • Google Chrome 119
  • Microsoft Edge 119

版本 1.39

向您的expect添加自定义匹配器

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

test.spec.ts
import { expect as baseExpect } from '@playwright/test';
export const expect = baseExpect.extend({
async toHaveAmount(locator: Locator, expected: number, options?: { timeout?: number }) {
// ... see documentation for how to write matchers.
},
});

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

查看文档获取完整示例

合并测试夹具

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

fixtures.ts
import { mergeTests } from '@playwright/test';
import { test as dbTest } from 'database-test-utils';
import { test as a11yTest } from 'a11y-test-utils';

export const test = mergeTests(dbTest, a11yTest);
test.spec.ts
import { test } from './fixtures';

test('passes', async ({ database, page, a11y }) => {
// 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();
});

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

你可以将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 过程中不会下载浏览器。

推荐迁移方案

运行npx playwright install命令在npm 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工具

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工具需要以下步骤:

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

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

  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扩展中的新"Show trace viewer"按钮使用:

    Playwright UI Mode

  • UI模式和跟踪查看器会标记通过page.route()browserContext.route()处理器处理的网络请求,以及通过API testing发出的请求:

    Trace Viewer

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

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

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

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

⚠️ 重大变更

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

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

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

浏览器版本

  • Chromium 115.0.5790.13
  • Mozilla Firefox 113.0
  • WebKit 16.4

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

  • Google Chrome 114
  • Microsoft Edge 114

版本 1.34

亮点

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

  • 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.

    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 用于创建预配置的expect实例,包含自定义默认值如 timeoutsoft

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

    // 始终执行软断言。
    const softExpect = expect.configure({ soft: true });
  • 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() 方法,用于创建匹配两个定位器的组合定位器。

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

⚠️ 重大变更

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

    automation.ts
    import { chromium, firefox, webkit } from '@playwright/test';
    /* ... */
  • Node.js 14自2023年4月30日达到生命周期终止后不再受支持。

浏览器版本

  • Chromium 114.0.5735.26
  • Mozilla Firefox 113.0
  • WebKit 16.4

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

  • Google Chrome 113
  • Microsoft Edge 113

版本 1.33

定位器更新

  • 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();
  • 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();
  • 使用新的网页优先断言 expect(locator).toBeAttached() 来确保元素存在于页面的DOM中。不要与 expect(locator).toBeVisible() 混淆,后者确保元素既存在于DOM中又可见。

新API

⚠️ 重大变更

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

浏览器版本

  • Chromium 113.0.5672.53
  • Mozilla Firefox 112.0
  • WebKit 16.4

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

  • Google Chrome 112
  • Microsoft Edge 112

版本 1.32

UI模式介绍(预览版)

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

Playwright UI 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

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

其他

  • 跟踪查看器中的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

  • 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() 用于遍历所有匹配的元素:

    // 勾选所有复选框!
    const checkboxes = page.getByRole('checkbox');
    for (const checkbox of await checkboxes.all())
    await checkbox.check();
  • locator.selectOption() matches now by value or label:

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

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

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

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

    playwright.config.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中的实时定位器。 您可以在VSCode中悬停并编辑定位器,使其在打开的浏览器中高亮显示。
  • 代码生成中的实时定位器。 使用"探索"工具为页面上的任何元素生成定位器。

Locator Explorer

  • 代码生成和跟踪查看器暗色主题。 自动从操作系统设置中获取。

Dark Theme

测试运行器

新API

浏览器版本

  • Chromium 108.0.5359.29
  • Mozilla Firefox 106.0
  • WebKit 16.4

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

  • Google Chrome 107
  • Microsoft Edge 107

版本 1.27

定位器

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

await page.getByLabel('User Name').fill('John');

await page.getByLabel('Password').fill('secret-password');

await page.getByRole('button', { name: 'Sign in' }).click();

await expect(page.getByText('Welcome, John!')).toBeVisible();

所有相同的方法也可在 LocatorFrameLocatorFrame 类上使用。

其他亮点

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

    npx playwright test --workers=20%
  • 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,该字段指定了配置文件的路径(如果有的话)。

  • 正如v1.25版本所宣布的,Ubuntu 18系统将在2022年12月后停止支持。除此之外,从下一个Playwright版本开始,Ubuntu 18上将不再提供WebKit更新。

行为变更

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

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

浏览器版本

  • Chromium 107.0.5304.18
  • Mozilla Firefox 105.0.1
  • WebKit 16.0

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

  • Google Chrome 106
  • Microsoft Edge 106

版本 1.26

断言

其他亮点

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

行为变更

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

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

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

为了与网页规范保持一致,'domcontentloaded'值仅等待目标框架触发'DOMContentLoaded'事件。如果需要等待所有iframe加载完成,请使用waitUntil: 'load'

浏览器版本

  • Chromium 106.0.5249.30
  • Mozilla Firefox 104.0
  • WebKit 16.0

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

  • Google Chrome 105
  • Microsoft Edge 105

版本 1.25

VSCode 扩展

  • 实时观看测试运行情况并保持开发者工具处于打开状态。
  • 选择选择器。
  • 从当前页面状态录制新测试。

vscode extension screenshot

测试运行器

  • test.step() 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.dev');
    return await page.title();
    });
    console.log(pageTitle);
    });
  • 新增了 test.describe.fixme()

  • 新增 'interrupted' 测试状态。

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

公告

  • 🎁 我们现在提供Ubuntu 22.04 Jammy Jellyfish的Docker镜像:mcr.microsoft.com/playwright:v1.34.0-jammy
  • 🪦 这是最后一个支持 macOS 10.15 的版本(自 1.21 起已弃用)。
  • 🪦 这是最后一个支持 Node.js 12 的版本,我们建议升级到 Node.js LTS (16)。
  • ⚠️ Ubuntu 18现已弃用,自2022年12月起将不再受支持。

浏览器版本

  • Chromium 105.0.5195.19
  • Mozilla Firefox 103.0
  • WebKit 16.0

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

  • Google Chrome 104
  • Microsoft Edge 104

版本1.24

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

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

playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
webServer: [
{
command: 'npm run start',
url: 'http://127.0.0.1:3000',
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
},
{
command: 'npm run backend',
url: 'http://127.0.0.1:3333',
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
}
],
use: {
baseURL: 'http://localhost:3000/',
},
});

🐂 Debian 11 Bullseye 支持

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

Linux支持看起来是这样的:

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

🕵️ 匿名描述

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

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

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

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

🧩 组件测试更新

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

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

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优先断言更新

组件测试更新

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

其他

  • 如果有一个service worker妨碍了您的工作,现在可以通过新的上下文选项serviceWorkers轻松禁用它:

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

    const context = await browser.newContext({
    recordHar: {
    path: 'github.har.zip',
    }
    });
  • 如果您打算手动编辑HAR文件,建议使用"minimal" 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 (新增)
  • 400, 401, 402, 403 (新增)

版本 1.22

亮点

  • Components Testing (preview)

    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属性可访问名称来选择元素。

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

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

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

    const buttons = page.locator('role=button');
    // ...
    const submitButton = buttons.filter({ hasText: 'Submit' });
    await submitButton.click();
  • 新增面向网页的断言方法 expect(page).toHaveScreenshot()expect(locator).toHaveScreenshot(),这些方法会等待截图稳定化,从而提升测试可靠性。

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

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

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

版本 1.21

亮点

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

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

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

  • page.screenshot() 中新增 scale 选项,用于生成较小尺寸的截图。

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

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

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

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

行为变更

  • 现在默认启用运行TypeScript测试时的ESM支持。不再需要PLAYWRIGHT_EXPERIMENTAL_TS_ESM环境变量。
  • Docker镜像mcr.microsoft.com/playwright不再包含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();
  • 新增 maxDiffPixelsmaxDiffPixelRatio 选项,用于通过 expect().toMatchSnapshot() 进行精细化的截图比较:

    expect(await page.screenshot()).toMatchSnapshot({
    maxDiffPixels: 27, // 允许不超过27个差异像素
    });

    最便捷的方式是在 testConfig.expect 中统一指定 maxDiffPixelsmaxDiffPixelRatio

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

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

    playwright.config.ts
    export default {
    projects: [
    {
    name: 'smoke tests',
    grep: /@smoke/,
    },
    ],
    };
  • Trace Viewer 现在可以显示 API testing requests

  • locator.highlight() 通过视觉方式高亮显示元素,便于调试。

公告

  • 我们现在提供了一个专门的Python Docker镜像mcr.microsoft.com/playwright/python。如果您使用Python,请切换到该镜像。这是最后一个在我们的JavaScript Docker镜像mcr.microsoft.com/playwright中包含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 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

  • 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()并行运行它们。

其他更新

Playwright Test全局设置中的潜在重大变更

这一改动不太可能对您产生影响,如果您的测试仍能像之前一样正常运行,则无需采取任何行动。

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

浏览器版本

  • Chromium 100.0.4863.0
  • Mozilla Firefox 96.0.1
  • WebKit 15.4

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

  • Google Chrome 98
  • Microsoft Edge 98

版本 1.18

定位器改进

API测试改进

改进的TypeScript支持

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

创建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

框架定位器

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

Graphics

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

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

了解更多信息,请访问我们的文档

追踪查看器更新

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

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

  • Playwright Test 现在默认包含源代码追踪(可通过tracing选项关闭此功能)
  • Trace Viewer 现在会显示测试名称
  • 新增跟踪元数据标签页,显示浏览器详细信息
  • 快照现在包含URL栏

image

HTML Report Update

  • HTML report now supports dynamic filtering
  • Report is now a single static HTML file that could be sent by e-mail or as a slack attachment.

image

Ubuntu ARM64 支持 + 更多

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

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

    npx playwright install msedge

新API

版本 1.16

🎭 Playwright Test

API测试

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

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

要在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端点,请使用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测试指南

响应拦截

现在可以通过将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.dev');
expect(response.status()).toBe(200);
});

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

New HTML reporter

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

$ npx playwright test --reporter=html

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

html reporter

了解更多关于我们的记者的信息。

🎭 Playwright 库

locator.waitFor

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

在处理列表时特别方便:

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

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

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

Docker对Arm64架构的支持

Playwright Docker镜像现已发布支持Arm64架构,因此可在Apple Silicon上使用。

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

🎭 Playwright Trace Viewer

  • 跟踪查看器中的web优先断言
  • 使用npx playwright show-trace运行追踪查看器,并将追踪文件拖放到追踪查看器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 库

🖱️ 鼠标滚轮

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

📜 新版Headers API

以前无法获取响应的多个标头值。现在这已成为可能,并且还提供了额外的辅助函数:

🌈 强制色彩模拟

现在可以通过在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 命令行参数

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

浏览器版本

  • Chromium 96.0.4641.0
  • Mozilla Firefox 92.0
  • WebKit 15.0

版本 1.14

🎭 Playwright 库

⚡️ 新增"严格"模式

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

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

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

📍 全新 定位器API

定位器(Locator)表示对页面上元素的一个视图。它包含了在任何给定时刻检索元素所需的足够逻辑。

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

此外,定位器默认情况下是"严格"的

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

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

🧩 实验性 ReactVue 选择器引擎

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

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

了解更多信息,请参阅react选择器文档vue选择器文档

✨ 新增 nthvisible 选择器引擎

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

✅ 网页优先断言

expect 现在支持大量新的面向网页的断言功能。

考虑以下示例:

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

Playwright Test 将重新测试带有选择器 .status 的节点,直到获取的节点包含 "Submitted" 文本。它会不断重新获取节点并进行检查,直到满足条件或达到超时时间。您可以直接传递这个超时时间,也可以通过测试配置中的 testProject.expect 值一次性配置。

默认情况下,断言超时时间未设置,因此会无限等待,直到整个测试超时。

所有新断言列表:

⛓ 使用describe.serial的串行模式

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

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

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

🐾 使用test.step的Steps 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中公开。

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

要在测试期间启动服务器,请在配置文件中使用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团队从头构建的全新测试运行器,专门用于满足端到端测试需求:

  • 在所有浏览器上运行测试。
  • 并行执行测试。
  • 开箱即用,享受上下文隔离和合理的默认设置。
  • 在失败时捕获视频、截图和其他工件。
  • 将您的POMs(页面对象模型)集成为可扩展的测试固件。

安装:

npm i -D @playwright/test

简单测试 tests/foo.spec.ts:

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

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

运行中:

npx playwright test

👉 了解更多内容请查阅Playwright Test文档

🧟‍♂️ Playwright Trace Viewer 介绍

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

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

追踪记录是通过新的browserContext.tracing API实现的:

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

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

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

追踪记录稍后可以通过Playwright CLI进行检查:

npx playwright show-trace trace.zip

这将打开以下图形用户界面:

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:面向现代网页的全新测试自动化框架幻灯片

  • 我们讨论过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 is a new GUI tool to author and debug your tests.
    • 逐行调试您的Playwright脚本,支持播放、暂停和单步执行。
    • 通过记录用户操作来编写新脚本。
    • 生成元素选择器 通过悬停在元素上来为您的脚本生成选择器。
    • 设置 PWDEBUG=1 环境变量来启动检查器
  • 暂停脚本执行在headed模式下使用page.pause()。暂停页面会启动Playwright Inspector进行调试。
  • 新增 has-text 伪类用于CSS选择器。:has-text("example")会匹配任何内部某处包含"example"的元素,可能是在子元素或后代元素中。查看更多示例
  • 页面对话框现在会在执行期间自动关闭,除非配置了dialog事件的监听器。了解更多
  • Playwright for Python 现已稳定发布,提供符合Python习惯的蛇形命名法API,并预置了Docker镜像以便在CI/CD中运行测试。

浏览器版本

  • Chromium 90.0.4421.0
  • Mozilla Firefox 86.0b10
  • WebKit 14.1

新API

版本 1.8

新API

浏览器版本

  • Chromium 90.0.4392.0
  • Mozilla Firefox 85.0b5
  • WebKit 14.1

版本 1.7

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

新API

浏览器版本

  • Chromium 89.0.4344.0
  • Mozilla Firefox 84.0b9
  • WebKit 14.1