跳过主内容

断言

介绍

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

expect(success).toBeTruthy();

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

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

Playwright 将会重复测试测试 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()元素具有匹配的可访问描述 (accessible description)
await expect(locator).toHaveAccessibleName()元素具有匹配的可访问名称 (accessible name)
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()下拉框已选中选项
await expect(page).toHaveScreenshot()页面有截屏
await expect(page).toHaveTitle()页面有标题
await expect(page).toHaveURL()页面有 URL
await expect(response).toBeOK()响应状态码正常 (OK)

非重试断言

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

尽可能优先使用自动重试断言。对于需要重试的更复杂的断言,请使用 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 { 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 {
const expectation = this.isNot ? baseExpect(locator).not : baseExpect(locator);
await expectation.toHaveAttribute('data-amount', String(expected), options);
pass = true;
} catch (e: any) {
matcherResult = e.matcherResult;
pass = false;
}

if (this.isNot) {
pass =!pass;
}

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