跳到主要内容

发行说明

版本 1.52

亮点

  • 新增方法 expect(locator).toContainClass() 用于方便地断言元素的单个类名。

    await expect(page.getByRole('listitem', { name: 'Ship v1.52' })).toContainClass('done');
  • Aria 快照 增加了两个新属性:/children 用于严格匹配,以及 /url 用于链接。

    await expect(locator).toMatchAriaSnapshot(`
    - list
    - /children: equal
    - listitem: Feature A
    - listitem:
    - link "Feature B":
    - /url: "https://playwright.net.cn"
    `);

测试运行器

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

其他

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

破坏性变更

  • 在诸如 page.route() 等方法中的 Glob URL 模式不再支持 ?[]。我们建议改用正则表达式。
  • 方法 route.continue() 不再允许覆盖 Cookie 头。如果提供了 Cookie 头,它将被忽略,并且 cookie 将从浏览器的 cookie 存储中加载。要设置自定义 cookie,请使用 browserContext.addCookies()
  • macOS 13 现已弃用,将不再接收 WebKit 更新。请升级到更新的 macOS 版本以继续受益于最新的 WebKit 改进。

浏览器版本

  • Chromium 136.0.7103.25
  • Mozilla Firefox 137.0
  • WebKit 18.4

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

  • Google Chrome 135
  • Microsoft Edge 135

版本 1.51

用于 indexedDB 的 StorageState

  • browserContext.storageState() 新增选项 indexedDB 允许保存和恢复 IndexedDB 内容。当您的应用程序使用 IndexedDB API 来存储身份验证令牌(例如 Firebase 身份验证)时非常有用。

    以下是遵循身份验证指南的示例

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

复制为提示词

HTML 报告、跟踪查看器和 UI 模式中的错误新增“复制提示词”按钮。单击以复制包含错误消息和用于修复错误的有用上下文的预填充 LLM 提示词。

Copy prompt

过滤可见元素

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

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

HTML 报告中的 Git 信息

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

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

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

HTML 报告将在信息可用时显示此信息

Git 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 () => {
    // This step can time out separately from the test
    }, { timeout: 1000 });
    });
  • 新增方法 test.step.skip() 用于禁用测试步骤的执行。

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

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

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

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

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

  • 新增选项 testConfig.updateSourceMethod 定义了配置 testConfig.updateSnapshots 时更新源代码的方式。新增了 overwrite3-way 模式,这些模式将更改写入源代码,此外还有现有的 patch 模式用于创建补丁文件。

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

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

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

UI 更新

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

破坏性变更

浏览器版本

  • Chromium 133.0.6943.16
  • Mozilla Firefox 134.0
  • WebKit 18.2

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

  • Google Chrome 132
  • Microsoft Edge 132

版本 1.49

Aria 快照

新增断言 expect(locator).toMatchAriaSnapshot() 通过与表示为 YAML 的预期可访问性树进行比较来验证页面结构。

await page.goto('https://playwright.net.cn');
await expect(page.locator('body')).toMatchAriaSnapshot(`
- banner:
- heading /Playwright enables reliable/ [level=1]
- link "Get started"
- link "Star microsoft/playwright on GitHub"
- main:
- img "Browsers (Chromium, Firefox, WebKit)"
- heading "Any browser • Any platform • One API"
`);

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

aria 快照指南中了解更多信息。

测试运行器

破坏性变更:chromemsedge 通道切换到新的无头模式

如果您在 playwright.config.ts 中使用以下通道之一,此更改会影响您:

  • chrome, chrome-dev, chrome-beta, or chrome-canary
  • msedge, msedge-dev, msedge-beta, or 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 文档所说,

另一方面,新的无头模式是真正的 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 连接。以下是模拟 WebSocket 通信的简单示例,它通过响应 "request" 来处理 "response"

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

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

UI 更新

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

其他

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

浏览器版本

  • Chromium 130.0.6723.19
  • Mozilla Firefox 130.0
  • WebKit 18.0

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

  • Google Chrome 129
  • Microsoft Edge 129

版本 1.47

网络选项卡改进

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

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

Network tab now has filters

--tsconfig CLI 选项

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

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

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

您现在可以将 URLSearchParamsstring 作为查询参数传递给 APIRequestContext

test('query params', async ({ request }) => {
const searchParams = new URLSearchParams();
searchParams.set('userId', 1);
const response = await request.get(
'https://jsonplaceholder.typicode.com/posts',
{
params: searchParams // or as a string: 'userId=1'
}
);
// ...
});

其他

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

浏览器版本

  • Chromium 129.0.6668.29
  • Mozilla Firefox 130.0
  • WebKit 18.0

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

  • Google Chrome 128
  • Microsoft Edge 128

版本 1.46

TLS 客户端证书

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

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

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

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

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

--only-changed cli 选项

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

# Only run test files with uncommitted changes
npx playwright test --only-changed

# Only run test files changed relative to the "main" branch
npx playwright test --only-changed=main

组件测试:新增 router fixture

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

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

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

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

test.beforeEach(async ({ router }) => {
// install common handlers before each test
await router.use(...handlers);
});

test('example test', async ({ mount }) => {
// test as usual, your handlers are active
// ...
});

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

UI 模式 / 跟踪查看器更新

  • 测试注解现在显示在 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

利用新的 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');

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

测试运行器

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

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

    # Avoid TTY features that output ANSI control sequences
    PLAYWRIGHT_FORCE_TTY=0 npx playwright test

    # Enable TTY features, assuming a terminal width 80
    PLAYWRIGHT_FORCE_TTY=80 npx playwright test
  • 新增选项 testConfig.respectGitIgnoretestProject.respectGitIgnore 控制在搜索测试时是否排除与 .gitignore 模式匹配的文件。

  • 新增属性 timeout 现在可用于自定义 expect matchers。此属性会考虑 playwright.config.tsexpect.configure() 的配置。

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

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

其他

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

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

    // Press the common keyboard shortcut Control+S or Meta+S to trigger a "Save" operation.
    await page.keyboard.press('ControlOrMeta+S');
  • apiRequest.newContext() 新增属性 httpCredentials.send,该属性允许始终发送 Authorization 头或仅在响应 401 Unauthorized 时发送。

  • apiRequestContext.dispose() 新增选项 reason,该选项将包含在因上下文处置而中断的正在进行操作的错误消息中。

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

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

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

浏览器版本

  • Chromium 127.0.6533.5
  • Mozilla Firefox 127.0
  • WebKit 17.4

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

  • Google Chrome 126
  • Microsoft Edge 126

版本 1.44

新增 API

可访问性断言

  • expect(locator).toHaveAccessibleName() 检查元素是否具有指定的 accessible name

    const locator = page.getByRole('button');
    await expect(locator).toHaveAccessibleName('Submit');
  • expect(locator).toHaveAccessibleDescription() 检查元素是否具有指定的 accessible description

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

其他选项

  • apiRequestContext.fetch()multipart 选项现在接受 FormData 并支持具有相同名称的重复字段。

    const formData = new FormData();
    formData.append('file', new File(['let x = 2024;'], 'f1.js', { type: 'text/javascript' }));
    formData.append('file', new File(['hello'], 'f2.txt', { type: 'text/plain' }));
    context.request.post('https://example.com/uploadFiles', {
    multipart: formData
    });
  • expect(callback).toPass({ intervals }) 现在可以通过 expect.toPass.intervals 选项在 testConfig.expect 中进行全局配置,或在 testProject.expect 中按项目进行配置。

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

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

报告器 API

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

命令行

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

    第一次运行所有测试

    $ npx playwright test

    Running 103 tests using 5 workers
    ...
    2 failed
    [chromium] › my-test.spec.ts:8:5 › two ─────────────────────────────────────────────────────────
    [chromium] › my-test.spec.ts:13:5 › three ──────────────────────────────────────────────────────
    101 passed (30.0s)

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

    $ npx playwright test --last-failed

    Running 2 tests using 2 workers
    2 passed (1.2s)

浏览器版本

  • Chromium 125.0.6422.14
  • Mozilla Firefox 125.0.1
  • WebKit 17.4

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

  • Google Chrome 124
  • Microsoft Edge 124

版本 1.43

新 API

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

    // Clear all cookies.
    await context.clearCookies();
    // New: clear cookies with a particular name.
    await context.clearCookies({ name: 'session-id' });
    // New: clear cookies for a particular domain.
    await context.clearCookies({ domain: 'my-origin.com' });
  • 用于 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 或直接点击标签来按标签过滤。
  • 新快捷键
    • “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' }));
test('test customer login', {
tag: ['@fast', '@login'],
}, async ({ page }) => {
// ...
});

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

npx playwright test --grep @fast
  • --project 命令行 标志 现在支持 '*' 通配符
npx playwright test --project='*mobile*'
test('test full report', {
annotation: [
{ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/23180' },
{ type: 'docs', description: 'https://playwright.net.cn/docs/test-annotations#tag-tests' },
],
}, async ({ page }) => {
// ...
});

公告

  • ⚠️ Ubuntu 18 不再受支持。

浏览器版本

  • Chromium 123.0.6312.4
  • Mozilla Firefox 123.0
  • WebKit 17.4

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

  • Google Chrome 122
  • Microsoft Edge 123

版本 1.41

新 API

浏览器版本

  • Chromium 121.0.6167.57
  • Mozilla Firefox 121.0
  • WebKit 17.4

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

  • Google Chrome 120
  • Microsoft Edge 120

版本 1.40

测试生成器更新

Playwright Test Generator

生成断言的新工具

这是一个包含断言的生成测试示例:

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

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

新 API

其他变更

浏览器版本

  • Chromium 120.0.6099.28
  • Mozilla Firefox 119.0
  • WebKit 17.4

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

  • Google Chrome 119
  • Microsoft Edge 119

版本 1.39

为 expect 添加自定义匹配器

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

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

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

请参阅文档 获取完整示例

合并测试夹具

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

fixtures.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 期间不会下载浏览器。

推荐的迁移方法

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

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

备选迁移方法(不推荐)

@playwright/browser-chromium@playwright/browser-firefox@playwright/browser-webkit 添加为依赖项。这些包会在 npm install 期间下载相应的浏览器。请确保所有 Playwright 包的版本保持同步

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

浏览器版本

  • Chromium 117.0.5938.62
  • Mozilla Firefox 117.0
  • WebKit 17.0

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

  • Google Chrome 116
  • Microsoft Edge 116

版本 1.37

新工具 npx playwright merge-reports

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

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

  1. 在 CI 上运行时,向配置添加一个新的“blob”报告器

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

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

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

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

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

📚 支持 Debian 12 Bookworm

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

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 模式和 trace viewer 会标记使用 page.route()browserContext.route() 处理的网络请求,以及通过 API 测试 发出的请求

    Trace Viewer

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

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

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

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

⚠️ 重大变更

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

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

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

浏览器版本

  • Chromium 115.0.5790.13
  • Mozilla Firefox 113.0
  • WebKit 16.4

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

  • Google Chrome 114
  • Microsoft Edge 114

版本 1.34

亮点

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

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

    常见模式是带有相应 teardown 的 setup 依赖关系

    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)的预配置 expect 实例。

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

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

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

    export default defineConfig({
    // Run your local dev server before starting the tests
    webServer: {
    command: 'npm run start',
    url: 'http://127.0.0.1:3000',
    reuseExistingServer: !process.env.CI,
    stdout: 'pipe',
    stderr: 'pipe',
    },
    });
  • 新的 locator.and() 方法用于创建一个匹配两个定位器的定位器。

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

⚠️ 重大变更

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

    automation.ts
    import { chromium, firefox, webkit } from '@playwright/test';
    /* ... */
  • Node.js 14 不再受支持,因为它已于 2023 年 4 月 30 日达到生命周期结束

浏览器版本

  • Chromium 114.0.5735.26
  • Mozilla Firefox 113.0
  • WebKit 16.4

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

  • Google Chrome 113
  • Microsoft Edge 113

版本 1.33

定位器更新

  • 使用 locator.or() 创建一个匹配两个定位器中任意一个的定位器。考虑一个场景,您想点击一个“New email”按钮,但有时会弹出一个安全设置对话框。在这种情况下,您可以等待“New email”按钮或对话框出现,并采取相应行动:

    const newEmail = page.getByRole('button', { name: 'New email' });
    const dialog = page.getByText('Confirm security settings');
    await expect(newEmail.or(dialog)).toBeVisible();
    if (await dialog.isVisible())
    await page.getByRole('button', { name: 'Dismiss' }).click();
    await newEmail.click();
  • locator.filter() 中使用新选项 hasNothasNotText 来查找不匹配特定条件的元素。

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

新 API

⚠️ 重大变更

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

浏览器版本

  • Chromium 113.0.5672.53
  • Mozilla Firefox 112.0
  • WebKit 16.4

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

  • Google Chrome 112
  • Microsoft Edge 112

版本 1.32

推出 UI 模式(预览版)

新的 UI 模式允许您探索、运行和调试测试。附带内置的监视模式。

Playwright UI Mode

使用新标志 --ui 启用

npx playwright test --ui

新 API

⚠️ 组件测试的重大变更

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

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

浏览器版本

  • Chromium 112.0.5615.29
  • Mozilla Firefox 111.0
  • WebKit 16.4

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

  • Google Chrome 111
  • Microsoft Edge 111

版本 1.31

新 API

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

    使用依赖关系可以使全局 setup 生成跟踪和其它产物,在测试报告中查看 setup 步骤等。

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

    export default defineConfig({
    projects: [
    {
    name: 'setup',
    testMatch: /global.setup\.ts/,
    },
    {
    name: 'chromium',
    use: devices['Desktop Chrome'],
    dependencies: ['setup'],
    },
    {
    name: 'firefox',
    use: devices['Desktop Firefox'],
    dependencies: ['setup'],
    },
    {
    name: 'webkit',
    use: devices['Desktop Safari'],
    dependencies: ['setup'],
    },
    ],
    });
  • 新断言 expect(locator).toBeInViewport() 确保定位器指向与 viewport 相交的元素,这遵循了 Intersection Observer API 规范。

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

    // Make sure at least some part of element intersects viewport.
    await expect(button).toBeInViewport();

    // Make sure element is fully outside of viewport.
    await expect(button).not.toBeInViewport();

    // Make sure that at least half of the element intersects viewport.
    await expect(button).toBeInViewport({ ratio: 0.5 });

杂项

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

⚠️ 组件测试的重大变更

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

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

// Before

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

config 变量定义替换为 defineConfig 调用

// After

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

浏览器版本

  • Chromium 111.0.5563.19
  • Mozilla Firefox 109.0
  • WebKit 16.4

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

  • Google Chrome 110
  • Microsoft Edge 110

版本 1.30

浏览器版本

  • Chromium 110.0.5481.38
  • Mozilla Firefox 108.0.2
  • WebKit 16.4

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

  • Google Chrome 109
  • Microsoft Edge 109

版本 1.29

新 API

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

    await page.route('**/api/settings', async route => {
    // Fetch original settings.
    const response = await route.fetch();

    // Force settings theme to a predefined value.
    const json = await response.json();
    json.theme = 'Solorized';

    // Fulfill with modified data.
    await route.fulfill({ json });
    });
  • 新方法 locator.all() 用于迭代匹配的所有元素

    // Check all checkboxes!
    const checkboxes = page.getByRole('checkbox');
    for (const checkbox of await checkboxes.all())
    await checkbox.check();
  • locator.selectOption() 现在可以通过 value 或 label 进行匹配

    <select multiple>
    <option value="red">Red</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 中悬停和编辑定位器,以在打开的浏览器中突出显示它们。
  • **在 CodeGen 中实时定位器。** 使用“探索”工具为页面上的任何元素生成定位器。

Locator Explorer

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

Dark Theme

测试运行器

新 API

浏览器版本

  • Chromium 108.0.5359.29
  • Mozilla Firefox 106.0
  • WebKit 16.4

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

  • Google Chrome 107
  • Microsoft Edge 107

版本 1.27

定位器

使用这些新 API 编写定位器非常愉快

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

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

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

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

所有相同的方法也可用于 LocatorFrameLocatorFrame 类。

其他亮点

  • playwright.config.ts 中的 workers 选项现在接受百分比字符串来使用部分可用的 CPUs。您也可以通过命令行传入该选项

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

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

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

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

行为变更

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

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

浏览器版本

  • Chromium 107.0.5304.18
  • Mozilla Firefox 105.0.1
  • WebKit 16.0

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

  • Google Chrome 106
  • Microsoft Edge 106

版本 1.26

断言

其他亮点

  • apiRequestContext.get() 和其他方法的新选项 maxRedirects,用于限制重定向次数。
  • 新命令行标志 --pass-with-no-tests,允许在找不到测试文件时测试套件通过。
  • 新命令行标志 --ignore-snapshots,用于跳过快照预期,例如 expect(value).toMatchSnapshot()expect(page).toHaveScreenshot()

行为变更

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

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

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

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

浏览器版本

  • Chromium 106.0.5249.30
  • Mozilla Firefox 104.0
  • WebKit 16.0

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

  • Google Chrome 105
  • Microsoft Edge 105

版本 1.25

VSCode 扩展

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

vscode extension screenshot

测试运行器

  • test.step() 现在返回步骤函数的返回值

    test('should work', async ({ page }) => {
    const pageTitle = await test.step('get title', async () => {
    await page.goto('https://playwright.net.cn');
    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 | ✅ | ✅ | ✅ |

🕵️ 匿名 Describe

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

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

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

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

🧩 组件测试更新

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

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

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

亮点

  • 组件测试(预览版)

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

    典型的组件测试示例如下

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

    // Let's test component in a dark scheme!
    test.use({ colorScheme: 'dark' });

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

    // As with any Playwright test, assert locator text.
    await expect(component).toContainText('React');
    // Or do a screenshot 🚀
    await expect(component).toHaveScreenshot();
    // Or use any Playwright method
    await component.click();
    });

    我们的文档中了解更多。

  • Role 选择器,允许通过元素的 ARIA roleARIA attributesaccessible name 来选择元素。

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

    我们的文档中了解更多。

  • 新的 locator.filter() API,用于过滤现有的 locator

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

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

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

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

版本 1.21

亮点

  • 新的 Role 选择器,允许通过元素的 ARIA roleARIA attributesaccessible name 来选择元素。

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

    我们的文档中了解更多。

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

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

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

    // Poll the method until it returns an expected result.
    await expect.poll(async () => {
    const response = await page.request.get('https://api.example.com');
    return response.status();
    }).toBe(200);

    expect.poll 支持大多数同步匹配器,如 .toBe().toContain() 等。在我们的文档中了解更多。

行为变更

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

浏览器版本

  • Chromium 101.0.4951.26
  • Mozilla Firefox 98.0.2
  • WebKit 15.4

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

  • Google Chrome 100
  • Microsoft Edge 100

版本 1.20

亮点

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

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

    expect('Web is Awesome <3').toMatchSnapshot();
  • expect().toMatchSnapshot() 中新增 maxDiffPixelsmaxDiffPixelRatio 选项,用于更精细的截屏比较

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

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

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

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

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

  • locator.highlight() 以视觉方式显示元素,以便更轻松地调试。

公告

  • 我们现在发布了一个专门的 Python docker 镜像 mcr.microsoft.com/playwright/python。如果您使用 Python,请切换到此镜像。这是最后一个在我们的 javascript mcr.microsoft.com/playwright docker 镜像中包含 Python 的版本。
  • v1.20 是最后一个获得 macOS 10.15 Catalina 的 WebKit 更新的版本。请更新 macOS 以继续使用最新最棒的 WebKit!

浏览器版本

  • Chromium 101.0.4921.0
  • Mozilla Firefox 97.0.1
  • WebKit 15.4

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

  • Google Chrome 99
  • Microsoft Edge 99

版本 1.19

Playwright Test 更新

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

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

    // Make a few checks that will not stop the test when failed...
    await expect.soft(page.locator('#status')).toHaveText('Success');
    await expect.soft(page.locator('#eta')).toHaveText('1 day');

    // ... and continue the test to check more things.
    await page.locator('#next-page').click();
    await expect.soft(page.locator('#title')).toHaveText('Make another order');

    我们的文档中了解更多

  • 您现在可以将**自定义 expect 消息**作为第二个参数传递给 expectexpect.soft 函数,例如

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

    错误信息如下所示

        Error: should be logged in

    Call log:
    - expect.toBeVisible with timeout 5000ms
    - waiting for "getByText('Name')"


    2 |
    3 | test('example test', async({ page }) => {
    > 4 | await expect(page.locator('text=Name'), 'should be logged in').toBeVisible();
    | ^
    5 | });
    6 |

    我们的文档中了解更多

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

其他更新

  • Locator 现在支持 has 选项,确保它包含另一个 locator

    await page.locator('article', {
    has: page.locator('.highlight'),
    }).click();

    locator 文档中了解更多

  • 新的 locator.page()

  • page.screenshot()locator.screenshot() 现在自动隐藏闪烁的光标

  • Playwright Codegen 现在生成 locator 和 frame locator

  • testConfig.webServer 中新增 url 选项,确保您的 Web 服务器在运行测试前就绪

  • 新的 testInfo.errorstestResult.errors,包含所有失败的断言和软断言。

Playwright Test Global Setup 中潜在的破坏性变更

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

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

浏览器版本

  • Chromium 100.0.4863.0
  • Mozilla Firefox 96.0.1
  • WebKit 15.4

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

  • Google Chrome 98
  • Microsoft Edge 98

版本 1.18

Locator 改进

测试 API 改进

改进的 TypeScript 支持

  1. Playwright Test 现在遵循 tsconfig.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

Frame Locator

Playwright 1.17 引入了 frame locator - 用于定位页面上的 iframe。Frame locator 捕获足以检索 iframe 然后在该 iframe 中定位元素的逻辑。Frame locator 默认是严格的,会等待 iframe 出现,并可在 Web 优先断言中使用。

Graphics

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

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

我们的文档中了解更多。

Trace Viewer 更新

Playwright Trace Viewer 现在可以在线访问:https://trace.playwright.dev!只需将您的 trace.zip 文件拖放到此处即可查看其内容。

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

  • Playwright Test 跟踪现在默认包含源文件(可以使用 tracing 选项关闭)
  • Trace Viewer 现在显示测试名称
  • 新的跟踪元数据选项卡,包含浏览器详细信息
  • 快照现在包含 URL 地址栏

image

HTML 报告更新

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

image

支持 Ubuntu ARM64 及更多

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

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

    npx playwright install msedge

新 API

版本 1.16

🎭 Playwright Test

API 测试

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

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

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

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

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

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

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

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

在我们的API 测试指南中了解更多。

响应拦截

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

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

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

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

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

新的 HTML 报告器

使用 --reporter=html 或在 playwright.config.ts 文件中添加 reporter 条目来试用新的 HTML 报告器

$ npx playwright test --reporter=html

HTML 报告器包含所有测试及其失败信息,包括跟踪和图像工件。

html reporter

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

🎭 Playwright 库

locator.waitFor

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

在使用列表时特别方便

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

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

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

Arm64 Docker 支持

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

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

🎭 Playwright Trace Viewer

  • Trace Viewer 中的 Web 优先断言
  • 使用 npx playwright show-trace 运行 Trace Viewer,并将跟踪文件拖放到 Trace Viewer PWA 中
  • API 测试与 Trace Viewer 集成
  • 更好的动作目标视觉归属

了解更多关于Trace Viewer的信息。

浏览器版本

  • Chromium 97.0.4666.0
  • Mozilla Firefox 93.0
  • WebKit 15.4

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

  • Google Chrome 94
  • Microsoft Edge 94

版本 1.15

🎭 Playwright 库

🖱️ 鼠标滚轮

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

📜 新的 Headers API

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

🌈 Forced-Colors 模拟

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

新 API

🎭 Playwright Test

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

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

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

🛠 添加 --debug CLI 标志

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

浏览器版本

  • Chromium 96.0.4641.0
  • Mozilla Firefox 92.0
  • WebKit 15.0

版本 1.14

🎭 Playwright 库

⚡️ 新增“严格”模式

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

在操作调用中传入 strict: true 即可启用。

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

📍 新增 定位符 API

定位符表示页面上元素的一个视图。它捕获了随时检索元素所需的逻辑。

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

此外,定位符默认是“严格”的

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 测试

✅ Web 优先断言

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

考虑以下示例

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

Playwright 测试将使用选择器 .status 不断重新测试节点,直到获取的节点包含文本 "Submitted"。它将重复获取并检查节点,直到满足条件或达到超时。你可以传入此超时时间,或通过测试配置中的 testProject.expect 值一次性配置。

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

所有新断言列表

⛓ 使用 describe.serial 的串行模式

声明一组应始终按顺序运行的测试。如果其中一个测试失败,所有后续测试将被跳过。组中的所有测试将一起重试。

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

文档中了解更多信息。

🐾 使用 test.step 的步骤 API

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

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

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

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

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

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

playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
webServer: {
command: 'npm run start', // command to launch
url: 'http://127.0.0.1:3000', // url to await for
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
},
});

文档中了解更多信息。

浏览器版本

  • Chromium 94.0.4595.0
  • Mozilla Firefox 91.0
  • WebKit 15.0

版本 1.13

Playwright 测试

Playwright

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

工具

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

新增和修订的指南

浏览器版本

  • Chromium 93.0.4576.0
  • Mozilla Firefox 90.0
  • WebKit 14.2

新增 Playwright API

版本 1.12

⚡️ 隆重推出 Playwright 测试

Playwright Test 是 Playwright 团队专门为满足端到端测试需求而从头构建的新型测试运行器

  • 跨所有浏览器运行测试。
  • 并行执行测试。
  • 享受开箱即用的上下文隔离和合理的默认设置。
  • 在失败时捕获视频、屏幕截图及其他附带信息。
  • 将你的 POM 集成而可扩展的 fixtures。

安装

npm i -D @playwright/test

简单的测试用例 tests/foo.spec.ts

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

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

运行中

npx playwright test

👉 在Playwright 测试文档中阅读更多信息。

🧟‍♂️ 隆重推出 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.net.cn');

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

随后使用 Playwright CLI 检查追踪信息

npx playwright show-trace trace.zip

这将打开以下 GUI 界面

image

👉 在trace viewer 文档中阅读更多信息。

浏览器版本

  • Chromium 93.0.4530.0
  • Mozilla Firefox 89.0
  • WebKit 14.2

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

  • Google Chrome 91
  • Microsoft Edge 91

新增 API

版本 1.11

🎥 新视频:Playwright: A New Test Automation Framework for the Modern Web幻灯片

  • 我们讨论了 Playwright
  • 展示了幕后的工程工作
  • 进行了新功能实时演示 ✨
  • 特别感谢 applitools 主办本次活动并邀请我们!

浏览器版本

  • Chromium 92.0.4498.0
  • Mozilla Firefox 89.0b6
  • WebKit 14.2

新增 API

版本 1.10

  • Playwright for Java v1.10 现已稳定
  • 使用 新通道 API 针对 Google ChromeMicrosoft Edge 的稳定通道运行 Playwright。
  • Chromium 屏幕截图在 Mac & Windows 上速度快

捆绑的浏览器版本

  • Chromium 90.0.4430.0
  • Mozilla Firefox 87.0b10
  • WebKit 14.2

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

  • Google Chrome 89
  • Microsoft Edge 89

新增 API

版本 1.9

  • Playwright Inspector 是一个新的 GUI 工具,用于编写和调试测试。
    • 对 Playwright 脚本进行逐行调试,支持播放、暂停和单步执行。
    • 通过记录用户操作来编写新脚本。
    • 通过将鼠标悬停在元素上为脚本生成元素选择器
    • 设置 PWDEBUG=1 环境变量以启动 Inspector
  • 在有头模式下使用 page.pause() 暂停脚本执行。暂停页面将启动 Playwright Inspector 进行调试。
  • CSS 选择器新增 has-text 伪类:has-text("example") 匹配任何包含 "example" 文本的元素,可能在其内部的某个位置,包括子元素或后代元素。查看更多示例
  • 页面对话框在执行期间现在会自动关闭,除非配置了 dialog 事件的监听器。了解更多关于此内容。
  • Playwright for Python 现已稳定,具有惯用的 snake case API 和预构建的 Docker 镜像,可在 CI/CD 中运行测试。

浏览器版本

  • Chromium 90.0.4421.0
  • Mozilla Firefox 86.0b10
  • WebKit 14.1

新增 API

版本 1.8

新增 API

浏览器版本

  • Chromium 90.0.4392.0
  • Mozilla Firefox 85.0b5
  • WebKit 14.1

版本 1.7

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

新增 API

浏览器版本

  • Chromium 89.0.4344.0
  • Mozilla Firefox 84.0b9
  • WebKit 14.1