跳到主要内容

断言

简介

Playwright 以 expect 函数的形式包含测试断言。要进行断言,请调用 expect(value) 并选择一个反映期望的匹配器。 有许多通用匹配器,例如 toEqualtoContaintoBeTruthy,可用于断言任何条件。

expect(success).toBeTruthy();

Playwright 还包括 Web 特定的 异步匹配器,它们将等待直到满足预期条件。 考虑以下示例

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

Playwright 将重新测试 test id 为 status 的元素,直到获取的元素具有 "Submitted" 文本。 它将反复重新获取元素并检查它,直到满足条件或达到超时时间。 您可以传递此超时时间,也可以通过测试配置中的 testConfig.expect 值配置一次。

默认情况下,断言的超时时间设置为 5 秒。 了解更多关于各种超时的信息。

自动重试断言

以下断言将重试,直到断言通过或达到断言超时时间。 请注意,重试断言是异步的,因此您必须 await 它们。

断言描述
await expect(locator).toBeAttached()元素已附加
await expect(locator).toBeChecked()复选框已选中
await expect(locator).toBeDisabled()元素已禁用
await expect(locator).toBeEditable()元素可编辑
await expect(locator).toBeEmpty()容器为空
await expect(locator).toBeEnabled()元素已启用
await expect(locator).toBeFocused()元素已聚焦
await expect(locator).toBeHidden()元素不可见
await expect(locator).toBeInViewport()元素与视口相交
await expect(locator).toBeVisible()元素可见
await expect(locator).toContainText()元素包含文本
await expect(locator).toHaveAccessibleDescription()元素具有匹配的 可访问描述
await expect(locator).toHaveAccessibleName()元素具有匹配的 可访问名称
await expect(locator).toHaveAttribute()元素具有 DOM 属性
await expect(locator).toHaveClass()元素具有 class 属性
await expect(locator).toHaveCount()列表具有确切数量的子元素
await expect(locator).toHaveCSS()元素具有 CSS 属性
await expect(locator).toHaveId()元素具有 ID
await expect(locator).toHaveJSProperty()元素具有 JavaScript 属性
await expect(locator).toHaveRole()元素具有特定的 ARIA 角色
await expect(locator).toHaveScreenshot()元素具有屏幕截图
await expect(locator).toHaveText()元素匹配文本
await expect(locator).toHaveValue()输入框具有值
await expect(locator).toHaveValues()Select 元素已选择选项
await expect(page).toHaveScreenshot()页面具有屏幕截图
await expect(page).toHaveTitle()页面具有标题
await expect(page).toHaveURL()页面具有 URL
await expect(response).toBeOK()响应具有 OK 状态

非重试断言

这些断言允许测试任何条件,但不自动重试。 大多数时候,网页异步显示信息,使用非重试断言可能会导致测试不稳定。

尽可能首选自动重试断言。 对于需要重试的更复杂的断言,请使用 expect.pollexpect.toPass

断言描述
expect(value).toBe()值相同
expect(value).toBeCloseTo()数字近似相等
expect(value).toBeDefined()值不是 undefined
expect(value).toBeFalsy()值为 falsy,例如 false0null 等。
expect(value).toBeGreaterThan()数字大于
expect(value).toBeGreaterThanOrEqual()数字大于或等于
expect(value).toBeInstanceOf()对象是类的实例
expect(value).toBeLessThan()数字小于
expect(value).toBeLessThanOrEqual()数字小于或等于
expect(value).toBeNaN()值为 NaN
expect(value).toBeNull()值为 null
expect(value).toBeTruthy()值为 truthy,即不是 false0null 等。
expect(value).toBeUndefined()值为 undefined
expect(value).toContain()字符串包含子字符串
expect(value).toContain()数组或集合包含元素
expect(value).toContainEqual()数组或集合包含相似的元素
expect(value).toEqual()值相似 - 深度相等和模式匹配
expect(value).toHaveLength()数组或字符串具有长度
expect(value).toHaveProperty()对象具有属性
expect(value).toMatch()字符串匹配正则表达式
expect(value).toMatchObject()对象包含指定的属性
expect(value).toStrictEqual()值相似,包括属性类型
expect(value).toThrow()函数抛出错误
expect(value).any()匹配类/原始类型的任何实例
expect(value).anything()匹配任何内容
expect(value).arrayContaining()数组包含特定的元素
expect(value).closeTo()数字近似相等
expect(value).objectContaining()对象包含特定的属性
expect(value).stringContaining()字符串包含子字符串
expect(value).stringMatching()字符串匹配正则表达式

否定匹配器

一般来说,我们可以通过在匹配器前面添加 .not 来期望相反的情况为真

expect(value).not.toEqual(0);
await expect(locator).not.toContainText('some text');

软断言

默认情况下,断言失败将终止测试执行。 Playwright 还支持软断言:失败的软断言不会终止测试执行,但会将测试标记为失败。

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

// ... and continue the test to check more things.
await page.getByRole('link', { name: 'next page' }).click();
await expect.soft(page.getByRole('heading', { name: 'Make another order' })).toBeVisible();

在测试执行期间的任何时候,您都可以检查是否存在任何软断言失败

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

// Avoid running further if there were soft assertion failures.
expect(test.info().errors).toHaveLength(0);

请注意,软断言仅适用于 Playwright 测试运行器。

自定义 expect 消息

您可以将自定义 expect 消息指定为 expect 函数的第二个参数,例如

await expect(page.getByText('Name'), 'should be logged in').toBeVisible();

此消息将显示在报告器中,无论是对于通过还是失败的 expect,从而提供有关断言的更多上下文。

当 expect 通过时,您可能会看到类似这样的成功步骤

✅ should be logged in    @example.spec.ts:18

当 expect 失败时,错误将如下所示

    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.getByText('Name'), 'should be logged in').toBeVisible();
| ^
5 | });
6 |

软断言也支持自定义消息

expect.soft(value, 'my soft assertion').toBe(56);

expect.configure

您可以创建自己的预配置 expect 实例,使其具有自己的默认值,例如 timeoutsoft

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

// Always do soft assertions.
const softExpect = expect.configure({ soft: true });
await softExpect(locator).toHaveText('Submit');

expect.poll

您可以使用 expect.poll 将任何同步 expect 转换为异步轮询的 expect。

以下方法将轮询给定的函数,直到它返回 HTTP 状态 200

await expect.poll(async () => {
const response = await page.request.get('https://api.example.com');
return response.status();
}, {
// Custom expect message for reporting, optional.
message: 'make sure API eventually succeeds',
// Poll for 10 seconds; defaults to 5 seconds. Pass 0 to disable timeout.
timeout: 10000,
}).toBe(200);

您还可以指定自定义轮询间隔

await expect.poll(async () => {
const response = await page.request.get('https://api.example.com');
return response.status();
}, {
// Probe, wait 1s, probe, wait 2s, probe, wait 10s, probe, wait 10s, probe
// ... Defaults to [100, 250, 500, 1000].
intervals: [1_000, 2_000, 10_000],
timeout: 60_000
}).toBe(200);

expect.toPass

您可以重试代码块,直到它们成功通过。

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

您还可以指定自定义超时和重试间隔

await expect(async () => {
const response = await page.request.get('https://api.example.com');
expect(response.status()).toBe(200);
}).toPass({
// Probe, wait 1s, probe, wait 2s, probe, wait 10s, probe, wait 10s, probe
// ... Defaults to [100, 250, 500, 1000].
intervals: [1_000, 2_000, 10_000],
timeout: 60_000
});

请注意,默认情况下 toPass 的超时时间为 0,并且不遵守自定义 expect 超时时间

使用 expect.extend 添加自定义匹配器

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

在此示例中,我们添加了一个自定义 toHaveAmount 函数。 自定义匹配器应返回一个 pass 标志,指示断言是否通过,以及一个 message 回调,该回调在断言失败时使用。

fixtures.ts
import { expect as baseExpect } from '@playwright/test';
import type { Page, Locator } from '@playwright/test';

export { test } from '@playwright/test';

export const expect = baseExpect.extend({
async toHaveAmount(locator: Locator, expected: number, options?: { timeout?: number }) {
const assertionName = 'toHaveAmount';
let pass: boolean;
let matcherResult: any;
try {
await baseExpect(locator).toHaveAttribute('data-amount', String(expected), options);
pass = true;
} catch (e: any) {
matcherResult = e.matcherResult;
pass = false;
}

const message = pass
? () => this.utils.matcherHint(assertionName, undefined, undefined, { isNot: this.isNot }) +
'\n\n' +
`Locator: ${locator}\n` +
`Expected: not ${this.utils.printExpected(expected)}\n` +
(matcherResult ? `Received: ${this.utils.printReceived(matcherResult.actual)}` : '')
: () => this.utils.matcherHint(assertionName, undefined, undefined, { isNot: this.isNot }) +
'\n\n' +
`Locator: ${locator}\n` +
`Expected: ${this.utils.printExpected(expected)}\n` +
(matcherResult ? `Received: ${this.utils.printReceived(matcherResult.actual)}` : '');

return {
message,
pass,
name: assertionName,
expected,
actual: matcherResult?.actual,
};
},
});

现在我们可以在测试中使用 toHaveAmount

example.spec.ts
import { test, expect } from './fixtures';

test('amount', async () => {
await expect(page.locator('.cart')).toHaveAmount(4);
});

与 expect 库的兼容性

注意

不要将 Playwright 的 expectexpect混淆。 后者未完全与 Playwright 测试运行器集成,因此请确保使用 Playwright 自己的 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 expect = mergeExpects(dbExpect, a11yExpect);
export const test = mergeTests(dbTest, a11yTest);
test.spec.ts
import { test, expect } from './fixtures';

test('passes', async ({ database }) => {
await expect(database).toHaveDatabaseUser('admin');
});