Skip to main content

断言

介绍

¥Introduction

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

¥Playwright includes test assertions in the form of expect function. To make an assertion, call expect(value) and choose a matcher that reflects the expectation. There are many generic matchers like toEqual, toContain, toBeTruthy that can be used to assert any conditions.

expect(success).toBeTruthy();

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

¥Playwright also includes web-specific async matchers that will wait until the expected condition is met. Consider the following example:

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

Playwright 将重新测试测试 ID 为 status 的元素,直到获取的元素具有 "Submitted" 文本。它将重新获取元素并一遍又一遍地检查它,直到满足条件或达到超时。你可以通过此超时或通过测试配置中的 testConfig.expect 值配置一次。

¥Playwright will be re-testing the element with the test id of status until the fetched element has the "Submitted" text. It will re-fetch the element and check it over and over, until the condition is met or until the timeout is reached. You can either pass this timeout or configure it once via the testConfig.expect value in the test config.

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

¥By default, the timeout for assertions is set to 5 seconds. Learn more about various timeouts.

自动重试断言

¥Auto-retrying assertions

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

¥The following assertions will retry until the assertion passes, or the assertion timeout is reached. Note that retrying assertions are async, so you must await them.

断言描述
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).toHaveAttribute()元素具有 DOM 属性
await expect(locator).toHaveClass()元素具有类属性
await expect(locator).toHaveCount()列表有确切的子级数量
await expect(locator).toHaveCSS()元素具有 CSS 属性
await expect(locator).toHaveId()元素有一个 ID
await expect(locator).toHaveJSProperty()元素具有 JavaScript 属性
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

不重试断言

¥Non-retrying assertions

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

¥These assertions allow to test any conditions, but do not auto-retry. Most of the time, web pages show information asynchronously, and using non-retrying assertions can lead to a flaky test.

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

¥Prefer auto-retrying assertions whenever possible. For more complex assertions that need to be retried, use expect.poll or expect.toPass.

断言描述
expect(value).toBe()值是一样的
expect(value).toBeCloseTo()数量大致相等
expect(value).toBeDefined()值不是 undefined
expect(value).toBeFalsy()值是假的,例如 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()值是真实的,即不是 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()字符串与正则表达式匹配

否定匹配器

¥Negating matchers

一般来说,通过在匹配器前面添加 .not,我们可以预期相反的情况成立:

¥In general, we can expect the opposite to be true by adding a .not to the front of the matchers:

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

软断言

¥Soft assertions

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

¥By default, failed assertion will terminate test execution. Playwright also supports soft assertions: failed soft assertions do not terminate test execution, but mark the test as failed.

// Make a few checks that will not stop the test when failed...
await expect.soft(page.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();

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

¥At any point during test execution, you can check whether there were any soft assertion failures:

// 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 测试运行程序。

¥Note that soft assertions only work with Playwright test runner.

自定义期望消息

¥Custom expect message

你可以指定自定义期望消息作为 expect 函数的第二个参数,例如:

¥You can specify a custom expect message as a second argument to the expect function, for example:

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

此消息将显示在报告器中,无论是通过预期还是失败预期,从而提供有关该断言的更多背景信息。

¥This message will be shown in reporters, both for passing and failing expects, providing more context about the assertion.

当 Expect 通过时,你可能会看到如下所示的成功步骤:

¥When expect passes, you might see a successful step like this:

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

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

¥When expect fails, the error would look like this:

    Error: should be logged in

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


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

软断言还支持自定义消息:

¥Soft assertions also support custom message:

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

expect.configure

你可以创建自己的预配置 expect 实例以拥有自己的默认值,例如 timeoutsoft

¥You can create your own pre-configured expect instance to have its own defaults such as timeout and soft.

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 转换为异步轮询。

¥You can convert any synchronous expect to an asynchronous polling one using expect.poll.

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

¥The following method will poll given function until it returns HTTP status 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);

你还可以指定自定义轮询间隔:

¥You can also specify custom polling intervals:

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

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

¥You can retry blocks of code until they are passing successfully.

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

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

¥You can also specify custom timeout and retry intervals:

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,并且不遵守自定义 预计超时

¥Note that by default toPass has timeout 0 and does not respect custom expect timeout.

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

¥Add custom matchers using expect.extend

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

¥You can extend Playwright assertions by providing custom matchers. These matchers will be available on the expect object.

在此示例中,我们添加自定义 toHaveAmount 函数。自定义匹配器应返回 message 回调和 pass 标志,指示断言是否通过。

¥In this example we add a custom toHaveAmount function. Custom matcher should return a message callback and a pass flag indicating whether the assertion passed.

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: ${this.isNot ? '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 进行测试。

¥Now we can use toHaveAmount in the test.

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

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

不要将 Playwright 的 expectexpect 混淆。后者未与 Playwright 测试运行程序完全集成,因此请确保使用 Playwright 自己的 expect

¥Do not confuse Playwright's expect with the expect library. The latter is not fully integrated with Playwright test runner, so make sure to use Playwright's own expect.

组合来自多个模块的自定义匹配器

¥Combine custom matchers from multiple modules

你可以组合来自多个文件或模块的自定义匹配器。

¥You can combine custom matchers from multiple files or modules.

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