Skip to main content

发布说明

版本 1.27

定位器 (Locators)

有了这些新的 API,编写定位器将变得非常愉快:

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

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

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

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

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

其他亮点

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

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

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

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

行为变更

  • expect(locator).toHaveAttribute(name, value[, options]) 使用空值不再匹配缺失的属性。例如,当 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(url[, options]) 和其他方法的新选项 maxRedirects 以限制重定向计数。
  • 新的命令行标志 --pass-with-no-tests,允许在未找到文件时通过测试套件。
  • 新的命令行标志 --ignore-snapshots 以跳过快照期望,例如 expect(value).toMatchSnapshot()expect(page).toHaveScreenshot()

行为变更

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

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

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

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

浏览器版本

  • Chromium 106.0.5249.30
  • Mozilla Firefox 104.0
  • WebKit 16.0

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

  • Google Chrome 105
  • Microsoft Edge 105

版本 1.25

VSCode 扩展

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

vscode extension screenshot

测试运行器

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

    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(title, callback)

  • 新的 'interrupted' 测试状态。

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

公告

  • 🎁 我们现在发布 Ubuntu 22.04 Jammy Jellyfish docker 镜像:mcr.microsoft.com/playwright:v1.28.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 type { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
webServer: [
{
command: 'npm run start',
port: 3000,
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
},
{
command: 'npm run backend',
port: 3333,
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
}
],
use: {
baseURL: 'http://localhost:3000/',
},
};
export default config;

🐂 Debian 11 Bullseye 支持

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

Linux 支持如下:

Ubuntu 18.04Ubuntu 20.04Ubuntu 22.04Debian 11
Chromium
WebKit
Firefox

🕵️ 匿名 Describe

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

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

网络重放 (Network Replay)

现在,您可以将网络流量记录到 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(har[, options])browserContext.routeFromHAR(har[, options])HAR 文件提供匹配的响应:

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

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

高级路由

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

考虑以下示例:

// 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'];
route.fallback({ headers });
});
});

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

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

Web-First 断言更新

组件测试更新

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

杂项

  • 如果有 service worker 妨碍您,您现在可以使用新的上下文选项 serviceWorkers 轻松禁用它:

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

    const context = await browser.newContext({
    recordHar: {
    path: 'github.har.zip',
    }
    });
  • 如果您打算手动编辑 HAR,请考虑使用 "minimal" 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.28.0-jammy

⚠️ 破坏性变更 ⚠️

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

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

版本 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([options]) API 用于过滤现有定位器

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

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

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

    新的 expect(page).toHaveScreenshot(name[, options]) 将屏幕截图保存在与 expect(screenshot).toMatchSnapshot(name[, options]) 相同的位置。

版本 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([options]) 中的新 scale 选项,用于较小尺寸的屏幕截图。

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

  • 新方法 expect.poll 等待任意条件:

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

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

行为变更

  • 运行 TypeScript 测试时的 ESM 支持现在默认启用。不再需要 PLAYWRIGHT_EXPERIMENTAL_TS_ESM 环境变量。
  • mcr.microsoft.com/playwright docker 镜像不再包含 Python。请使用 mcr.microsoft.com/playwright/python 作为预装了 Python 的 Playwright-ready docker 镜像。
  • Playwright 现在通过 locator.setInputFiles(files[, options]) 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([options])locator.screenshot([options])elementHandle.screenshot([options]) 的新选项:

    • 选项 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,请切换到它。这是包含 Python 在我们的 javascript mcr.microsoft.com/playwright docker 镜像中的最后一个版本。
  • 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 现在支持 软断言 (soft assertions)。失败的软断言

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

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

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

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

  • 您现在可以将 自定义错误消息 指定为 expectexpect.soft 函数的第二个参数,例如:

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

其他更新

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

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

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

浏览器版本

  • Chromium 100.0.4863.0
  • Mozilla Firefox 96.0.1
  • WebKit 15.4

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

  • Google Chrome 98
  • Microsoft Edge 98

版本 1.18

Locator 改进

测试 API 改进

改进的 TypeScript 支持

  1. Playwright Test 现在遵循 tsconfig.jsonbaseUrlpaths,因此您可以使用别名
  2. 有一个新的环境变量 PW_EXPERIMENTAL_TS_ESM,允许在您的 TS 代码中导入 ESM 模块,而无需编译步骤。导入 esm 模块时不要忘记 .js 后缀。按如下方式运行测试:
npm i --save-dev @playwright/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(fixtures) 引入的任何 fixture 都可以在 testProject.use 配置部分中覆盖。例如,

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

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

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

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

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

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

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

浏览器版本

  • Chromium 99.0.4812.0
  • Mozilla Firefox 95.0
  • WebKit 15.4

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

  • Google Chrome 97
  • Microsoft Edge 97

版本 1.17

Frame Locators

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

Graphics

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

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

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

Trace Viewer 更新

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

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

  • Playwright Test traces 现在默认包含源代码(可以通过 tracing 选项关闭)
  • Trace Viewer 现在显示测试名称
  • 带有浏览器详细信息的新 trace 元数据选项卡
  • 快照现在有 URL 栏

image

HTML 报告更新

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

image

Ubuntu ARM64 支持及更多

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

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

    npx playwright install msedge

新 API

版本 1.16

🎭 Playwright Test

API 测试

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

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

要代表 Playwright 的 Page 执行请求,请使用 新的 page.request API

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

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

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

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

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

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

响应拦截

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

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

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

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

阅读有关 响应拦截 的更多信息。

新的 HTML 报告器

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

$ npx playwright test --reporter=html

HTML 报告器包含有关测试及其失败的所有信息,包括显示 trace 和图像工件。

html reporter

阅读有关 我们的报告器 的更多信息。

🎭 Playwright Library

locator.waitFor

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

在处理列表时特别方便:

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

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

阅读有关 locator.waitFor([options]) 的更多信息。

对 Arm64 的 Docker 支持

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

阅读有关 Docker 集成 的更多信息。

🎭 Playwright Trace Viewer

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

阅读更多关于 Trace Viewer 的信息。

浏览器版本

  • Chromium 97.0.4666.0
  • Mozilla Firefox 93.0
  • WebKit 15.4

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

  • Google Chrome 94
  • Microsoft Edge 94

Version 1.15

🎭 Playwright 库

🖱️ 鼠标滚轮

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

📜 新的 Headers API

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

🌈 强制颜色模拟 (Forced-Colors emulation)

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

新 API

🎭 Playwright Test

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

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

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

🛠 添加 --debug CLI 标志

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

浏览器版本

  • Chromium 96.0.4641.0
  • Mozilla Firefox 92.0
  • WebKit 15.0

Version 1.14

🎭 Playwright 库

⚡️ 新的 "strict" 模式

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

在您的操作调用中传递 strict: true 以启用。

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

📍 新的 Locators API

Locator 代表页面上元素及其视图。它捕获足以在任何给定时刻检索元素的逻辑。

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

此外,locators 默认是 "strict" 的

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

更多信息请参阅 文档

🧩 实验性的 ReactVue 选择器引擎

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

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

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

✨ 新的 nthvisible 选择器引擎

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

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

🎭 Playwright Test

✅ Web 优先断言 (Web-First Assertions)

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

考虑以下示例:

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

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

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

所有新断言的列表:

⛓ 使用 describe.serial 的串行模式

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

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

更多信息请参阅 文档

🐾 使用 test.step 的步骤 API

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

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

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

步骤信息暴露在 reporters API 中。

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

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

// playwright.config.ts
import type { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
webServer: {
command: 'npm run start', // 启动命令
port: 3000, // 等待的端口
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
},
};
export default config;

更多信息请参阅 文档

浏览器版本

  • Chromium 94.0.4595.0
  • Mozilla Firefox 91.0
  • WebKit 15.0

Version 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

Version 1.12

⚡️ 介绍 Playwright Test

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

  • 跨所有浏览器运行测试。
  • 并行执行测试。
  • 开箱即用的上下文隔离和合理的默认值。
  • 在失败时捕获视频、屏幕截图和其他工件。
  • 将您的 POM 集成为可扩展的 fixtures。

安装:

npm i -D @playwright/test

简单测试 tests/foo.spec.ts

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

test('basic test', async ({ page }) => {
await page.goto('https://playwright.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 traces。Playwright traces 允许您检查:

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

使用新的 browserContext.tracing API 记录 Traces:

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

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

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

// 停止 tracing 并将其导出到 zip 归档中。
await context.tracing.stop({ path: 'trace.zip' });

稍后使用 Playwright CLI 检查 Traces:

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

Version 1.11

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

  • 我们谈到了 Playwright
  • 展示了幕后的工程工作
  • 演示了新功能的现场 demo ✨
  • 特别感谢 applitools 主办此次活动并邀请我们!

浏览器版本

  • Chromium 92.0.4498.0
  • Mozilla Firefox 89.0b6
  • WebKit 14.2

新 API

Version 1.10

捆绑的浏览器版本

  • Chromium 90.0.4430.0
  • Mozilla Firefox 87.0b10
  • WebKit 14.2

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

  • Google Chrome 89
  • Microsoft Edge 89

新 API

Version 1.9

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

浏览器版本

  • Chromium 90.0.4421.0
  • Mozilla Firefox 86.0b10
  • WebKit 14.1

新 API

Version 1.8

新 API

浏览器版本

  • Chromium 90.0.4392.0
  • Mozilla Firefox 85.0b5
  • WebKit 14.1

Version 1.7

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

新 API

浏览器版本

  • Chromium 89.0.4344.0
  • Mozilla Firefox 84.0b9
  • WebKit 14.1