Skip to main content

LocatorAssertions

LocatorAssertions 类提供了断言方法,可用于在测试中对 Locator 状态进行断言。

🌐 The LocatorAssertions class provides assertion methods that can be used to make assertions about the Locator state in the tests.

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

test('status becomes submitted', async ({ page }) => {
// ...
await page.getByRole('button').click();
await expect(page.locator('.status')).toHaveText('Submitted');
});

方法

🌐 Methods

toBeAttached

Added in: v1.33 locatorAssertions.toBeAttached

确保 Locator 指向一个已 连接 到文档或 ShadowRoot 的元素。

🌐 Ensures that Locator points to an element that is connected to a Document or a ShadowRoot.

用法

await expect(page.getByText('Hidden text')).toBeAttached();

参数

  • options Object (optional)
    • attached boolean (optional)#

    • timeout number (optional)#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toBeChecked

Added in: v1.20 locatorAssertions.toBeChecked

确保 Locator 指向已选中的输入项。

🌐 Ensures the Locator points to a checked input.

用法

const locator = page.getByLabel('Subscribe to newsletter');
await expect(locator).toBeChecked();

参数

  • options Object (optional)
    • checked boolean (optional) Added in: v1.18#

      提供要断言的状态。默认情况下断言输入进行检查。当 indeterminate 设置为 true 时,无法使用此选项。

    • indeterminate boolean (optional) Added in: v1.50#

      断言元素处于不确定(混合)状态。仅支持复选框和单选按钮。当提供了 checked 时,此选项不能为 true。

    • timeout number (optional) Added in: v1.18#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toBeDisabled

Added in: v1.20 locatorAssertions.toBeDisabled

确保 Locator 指向一个已禁用的元素。如果元素具有“disabled”属性或通过 'aria-disabled' 被禁用,则该元素被视为已禁用。请注意,只有像 HTML buttoninputselecttextareaoptionoptgroup 这样的原生控件元素可以通过设置“disabled”属性来禁用。浏览器会忽略其他元素上的“disabled”属性。

🌐 Ensures the Locator points to a disabled element. Element is disabled if it has "disabled" attribute or is disabled via 'aria-disabled'. Note that only native control elements such as HTML button, input, select, textarea, option, optgroup can be disabled by setting "disabled" attribute. "disabled" attribute on other elements is ignored by the browser.

用法

const locator = page.locator('button.submit');
await expect(locator).toBeDisabled();

参数

  • options Object (optional)
    • timeout number (optional) Added in: v1.18#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toBeEditable

Added in: v1.20 locatorAssertions.toBeEditable

确保 Locator 指向可编辑的元素。

🌐 Ensures the Locator points to an editable element.

用法

const locator = page.getByRole('textbox');
await expect(locator).toBeEditable();

参数

  • options Object (optional)
    • editable boolean (optional) Added in: v1.26#

    • timeout number (optional) Added in: v1.18#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toBeEmpty

Added in: v1.20 locatorAssertions.toBeEmpty

确保 Locator 指向一个空的可编辑元素或没有文本的 DOM 节点。

🌐 Ensures the Locator points to an empty editable element or to a DOM node that has no text.

用法

const locator = page.locator('div.warning');
await expect(locator).toBeEmpty();

参数

  • options Object (optional)
    • timeout number (optional) Added in: v1.18#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toBeEnabled

Added in: v1.20 locatorAssertions.toBeEnabled

确保 Locator 指向一个已启用的元素。

🌐 Ensures the Locator points to an enabled element.

用法

const locator = page.locator('button.submit');
await expect(locator).toBeEnabled();

参数

  • options Object (optional)
    • enabled boolean (optional) Added in: v1.26#

    • timeout number (optional) Added in: v1.18#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toBeFocused

Added in: v1.20 locatorAssertions.toBeFocused

确保 Locator 指向一个已聚焦的 DOM 节点。

🌐 Ensures the Locator points to a focused DOM node.

用法

const locator = page.getByRole('textbox');
await expect(locator).toBeFocused();

参数

  • options Object (optional)
    • timeout number (optional) Added in: v1.18#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toBeHidden

Added in: v1.20 locatorAssertions.toBeHidden

确保 Locator 要么无法解析到任何 DOM 节点,要么解析到一个不可见的节点。

🌐 Ensures that Locator either does not resolve to any DOM node, or resolves to a non-visible one.

用法

const locator = page.locator('.my-element');
await expect(locator).toBeHidden();

参数

  • options Object (optional)
    • timeout number (optional) Added in: v1.18#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toBeInViewport

Added in: v1.31 locatorAssertions.toBeInViewport

确保 Locator 指向根据 intersection observer API 与视口相交的元素。

🌐 Ensures the Locator points to an element that intersects viewport, according to the intersection observer API.

用法

const locator = page.getByRole('button');
// Make sure at least some part of element intersects viewport.
await expect(locator).toBeInViewport();
// Make sure element is fully outside of viewport.
await expect(locator).not.toBeInViewport();
// Make sure that at least half of the element intersects viewport.
await expect(locator).toBeInViewport({ ratio: 0.5 });

参数

  • options Object (optional)
    • ratio number (optional)#

      元素与视口相交的最小比例。如果等于 0,则元素应与视口相交的比例为任意正数。默认值为 0

    • timeout number (optional)#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toBeVisible

Added in: v1.20 locatorAssertions.toBeVisible

确保 Locator 指向一个已附加且可见的 DOM 节点。

🌐 Ensures that Locator points to an attached and visible DOM node.

要检查列表中至少有一个元素可见,请使用 locator.first()

🌐 To check that at least one element from the list is visible, use locator.first().

用法

// A specific element is visible.
await expect(page.getByText('Welcome')).toBeVisible();

// At least one item in the list is visible.
await expect(page.getByTestId('todo-item').first()).toBeVisible();

// At least one of the two elements is visible, possibly both.
await expect(
page.getByRole('button', { name: 'Sign in' })
.or(page.getByRole('button', { name: 'Sign up' }))
.first()
).toBeVisible();

参数

  • options Object (optional)
    • timeout number (optional) Added in: v1.18#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

    • visible boolean (optional) Added in: v1.26#

返回


toContainClass

Added in: v1.52 locatorAssertions.toContainClass

确保 Locator 指向具有指定 CSS 类的元素。断言值中的所有类(以空格分隔)都必须出现在 Element.classList 中,顺序可以任意。

🌐 Ensures the Locator points to an element with given CSS classes. All classes from the asserted value, separated by spaces, must be present in the Element.classList in any order.

用法

<div class='middle selected row' id='component'></div>
const locator = page.locator('#component');
await expect(locator).toContainClass('middle selected row');
await expect(locator).toContainClass('selected');
await expect(locator).toContainClass('row middle');

当传递数组时,方法断言所在元素列表与预期类列表匹配。每个元素的类属性与数组中对应的类进行匹配:

🌐 When an array is passed, the method asserts that the list of elements located matches the corresponding list of expected class lists. Each element's class attribute is matched against the corresponding class in the array:

<div class='list'>
<div class='component inactive'></div>
<div class='component active'></div>
<div class='component inactive'></div>
</div>
const locator = page.locator('.list > .component');
await expect(locator).toContainClass(['inactive', 'active', 'inactive']);

参数

  • expected string | Array<string>#

    包含预期类名的字符串(以空格分隔),或用于断言多个元素的此类字符串列表。

  • options Object (optional)

    • timeout number (optional)#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toContainText

Added in: v1.20 locatorAssertions.toContainText

确保 Locator 指向包含给定文本的元素。在计算元素的文本内容时,将考虑所有嵌套元素。你也可以对该值使用正则表达式。

🌐 Ensures the Locator points to an element that contains the given text. All nested elements will be considered when computing the text content of the element. You can use regular expressions for the value as well.

用法

const locator = page.locator('.title');
await expect(locator).toContainText('substring');
await expect(locator).toContainText(/\d messages/);

如果你传递一个数组作为期望值,则期望为:

🌐 If you pass an array as an expected value, the expectations are:

  1. 定位器解析为元素列表。
  2. 此列表的子集中的元素分别包含预期数组中的文本。
  3. 匹配的元素子集与预期数组具有相同的顺序。
  4. 预期数组中的每个文本值都与列表中的某个元素匹配。

例如,考虑以下列表:

🌐 For example, consider the following list:

<ul>
<li>Item Text 1</li>
<li>Item Text 2</li>
<li>Item Text 3</li>
</ul>

让我们看看如何使用断言:

🌐 Let's see how we can use the assertion:

// ✓ Contains the right items in the right order
await expect(page.locator('ul > li')).toContainText(['Text 1', 'Text 3']);

// ✖ Wrong order
await expect(page.locator('ul > li')).toContainText(['Text 3', 'Text 2']);

// ✖ No item contains this text
await expect(page.locator('ul > li')).toContainText(['Some 33']);

// ✖ Locator points to the outer list element, not to the list items
await expect(page.locator('ul')).toContainText(['Text 3']);

参数

  • expected string | RegExp | Array<string | RegExp> Added in: v1.18#

    预期的子字符串或正则表达式或这些的列表。

  • options Object (optional)

    • ignoreCase boolean (optional) Added in: v1.23#

      是否执行不区分大小写的匹配。如果指定,ignoreCase 选项优先于相应的正则表达式标志。

    • timeout number (optional) Added in: v1.18#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

    • useInnerText boolean (optional) Added in: v1.18#

      在获取 DOM 节点文本时,是使用 element.innerText 还是 element.textContent

返回

详情

expected 参数是字符串时,Playwright 会在匹配前对实际文本和预期字符串中的空格和换行进行规范化。当使用正则表达式时,实际文本将按原样进行匹配。

🌐 When expected parameter is a string, Playwright will normalize whitespaces and line breaks both in the actual text and in the expected string before matching. When regular expression is used, the actual text is matched as is.


toHaveAccessibleDescription

Added in: v1.44 locatorAssertions.toHaveAccessibleDescription

确保 Locator 指向具有给定 可访问描述 的元素。

🌐 Ensures the Locator points to an element with a given accessible description.

用法

const locator = page.getByTestId('save-button');
await expect(locator).toHaveAccessibleDescription('Save results to disk');

参数

  • description string | RegExp#

    预期可访问描述。

  • options Object (optional)

    • ignoreCase boolean (optional)#

      是否执行不区分大小写的匹配。如果指定,ignoreCase 选项优先于相应的正则表达式标志。

    • timeout number (optional)#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toHaveAccessibleErrorMessage

Added in: v1.50 locatorAssertions.toHaveAccessibleErrorMessage

确保 Locator 指向具有指定 aria errormessage 的元素。

🌐 Ensures the Locator points to an element with a given aria errormessage.

用法

const locator = page.getByTestId('username-input');
await expect(locator).toHaveAccessibleErrorMessage('Username is required.');

参数

  • errorMessage string | RegExp#

    预期可访问的错误消息。

  • options Object (optional)

    • ignoreCase boolean (optional)#

      是否执行不区分大小写的匹配。如果指定,ignoreCase 选项优先于相应的正则表达式标志。

    • timeout number (optional)#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toHaveAccessibleName

Added in: v1.44 locatorAssertions.toHaveAccessibleName

确保 Locator 指向具有给定 可访问名称 的元素。

🌐 Ensures the Locator points to an element with a given accessible name.

用法

const locator = page.getByTestId('save-button');
await expect(locator).toHaveAccessibleName('Save to disk');

参数

  • name string | RegExp#

    预期可访问名称。

  • options Object (optional)

    • ignoreCase boolean (optional)#

      是否执行不区分大小写的匹配。如果指定,ignoreCase 选项优先于相应的正则表达式标志。

    • timeout number (optional)#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toHaveAttribute(name, value)

Added in: v1.20 locatorAssertions.toHaveAttribute(name, value)

确保 Locator 指向具有指定属性的元素。

🌐 Ensures the Locator points to an element with given attribute.

用法

const locator = page.locator('input');
await expect(locator).toHaveAttribute('type', 'text');

参数

  • name string Added in: v1.18#

    属性名称。

  • value string | RegExp Added in: v1.18#

    期望的属性值。

  • options Object (optional)

    • ignoreCase boolean (optional) Added in: v1.40#

      是否执行不区分大小写的匹配。如果指定,ignoreCase 选项优先于相应的正则表达式标志。

    • timeout number (optional) Added in: v1.18#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toHaveAttribute(name)

Added in: v1.39 locatorAssertions.toHaveAttribute(name)

确保 Locator 指向具有指定属性的元素。该方法将断言属性存在。

🌐 Ensures the Locator points to an element with given attribute. The method will assert attribute presence.

const locator = page.locator('input');
// Assert attribute existence.
await expect(locator).toHaveAttribute('disabled');
await expect(locator).not.toHaveAttribute('open');

用法

await expect(locator).toHaveAttribute(name);
await expect(locator).toHaveAttribute(name, options);

参数

  • name string#

    属性名称。

  • options Object (optional)

    • timeout number (optional)#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toHaveClass

Added in: v1.20 locatorAssertions.toHaveClass

确保 Locator 指向具有指定 CSS 类的元素。当提供字符串时,它必须与元素的 class 属性完全匹配。要匹配单个类,请使用 expect(locator).toContainClass()

🌐 Ensures the Locator points to an element with given CSS classes. When a string is provided, it must fully match the element's class attribute. To match individual classes use expect(locator).toContainClass().

用法

<div class='middle selected row' id='component'></div>
const locator = page.locator('#component');
await expect(locator).toHaveClass('middle selected row');
await expect(locator).toHaveClass(/(^|\s)selected(\s|$)/);

当传入一个数组时,该方法会断言定位到的元素列表与相应的预期类值列表匹配。每个元素的类属性都会与数组中的相应字符串或正则表达式进行匹配:

🌐 When an array is passed, the method asserts that the list of elements located matches the corresponding list of expected class values. Each element's class attribute is matched against the corresponding string or regular expression in the array:

const locator = page.locator('.list > .component');
await expect(locator).toHaveClass(['component', 'component selected', 'component']);

参数

  • expected string | RegExp | Array<string | RegExp> Added in: v1.18#

    预期的类或 RegExp 或这些的列表。

  • options Object (optional)

    • timeout number (optional) Added in: v1.18#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toHaveCount

Added in: v1.20 locatorAssertions.toHaveCount

确保 Locator 解析为确切数量的 DOM 节点。

🌐 Ensures the Locator resolves to an exact number of DOM nodes.

用法

const list = page.locator('list > .component');
await expect(list).toHaveCount(3);

参数

  • count number Added in: v1.18#

    预期计数。

  • options Object (optional)

    • timeout number (optional) Added in: v1.18#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toHaveCSS

Added in: v1.20 locatorAssertions.toHaveCSS

确保 Locator 解析为具有给定计算 CSS 样式的元素。

🌐 Ensures the Locator resolves to an element with the given computed CSS style.

用法

const locator = page.getByRole('button');
await expect(locator).toHaveCSS('display', 'flex');

参数

  • name string Added in: v1.18#

    CSS 属性名称。

  • value string | RegExp Added in: v1.18#

    CSS 属性值。

  • options Object (optional)

    • timeout number (optional) Added in: v1.18#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toHaveId

Added in: v1.20 locatorAssertions.toHaveId

确保 Locator 指向具有指定 DOM 节点 ID 的元素。

🌐 Ensures the Locator points to an element with the given DOM Node ID.

用法

const locator = page.getByRole('textbox');
await expect(locator).toHaveId('lastname');

参数

  • id string | RegExp Added in: v1.18#

    元素 ID。

  • options Object (optional)

    • timeout number (optional) Added in: v1.18#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toHaveJSProperty

Added in: v1.20 locatorAssertions.toHaveJSProperty

确保 Locator 指向具有指定 JavaScript 属性的元素。请注意,该属性可以是原始类型,也可以是普通可序列化的 JavaScript 对象。

🌐 Ensures the Locator points to an element with given JavaScript property. Note that this property can be of a primitive type as well as a plain serializable JavaScript object.

用法

const locator = page.locator('.component');
await expect(locator).toHaveJSProperty('loaded', true);

参数

  • name string Added in: v1.18#

    属性名称。

  • value Object Added in: v1.18#

    属性值

  • options Object (optional)

    • timeout number (optional) Added in: v1.18#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toHaveRole

Added in: v1.44 locatorAssertions.toHaveRole

确保 Locator 指向具有指定 ARIA 角色 的元素。

🌐 Ensures the Locator points to an element with a given ARIA role.

请注意,角色是作为字符串匹配的,不考虑 ARIA 角色层次。例如,在具有子类角色 "switch" 的元素上断言超类角色 "checkbox" 将会失败。

🌐 Note that role is matched as a string, disregarding the ARIA role hierarchy. For example, asserting a superclass role "checkbox" on an element with a subclass role "switch" will fail.

用法

const locator = page.getByTestId('save-button');
await expect(locator).toHaveRole('button');

参数

  • role "alert" | "alertdialog" | "application" | "article" | "banner" | "blockquote" | "button" | "caption" | "cell" | "checkbox" | "code" | "columnheader" | "combobox" | "complementary" | "contentinfo" | "definition" | "deletion" | "dialog" | "directory" | "document" | "emphasis" | "feed" | "figure" | "form" | "generic" | "grid" | "gridcell" | "group" | "heading" | "img" | "insertion" | "link" | "list" | "listbox" | "listitem" | "log" | "main" | "marquee" | "math" | "meter" | "menu" | "menubar" | "menuitem" | "menuitemcheckbox" | "menuitemradio" | "navigation" | "none" | "note" | "option" | "paragraph" | "presentation" | "progressbar" | "radio" | "radiogroup" | "region" | "row" | "rowgroup" | "rowheader" | "scrollbar" | "search" | "searchbox" | "separator" | "slider" | "spinbutton" | "status" | "strong" | "subscript" | "superscript" | "switch" | "tab" | "table" | "tablist" | "tabpanel" | "term" | "textbox" | "time" | "timer" | "toolbar" | "tooltip" | "tree" | "treegrid" | "treeitem"#

    所需的咏叹调角色。

  • options Object (optional)

    • timeout number (optional)#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toHaveScreenshot(name)

Added in: v1.23 locatorAssertions.toHaveScreenshot(name)

此函数将等到两个连续的定位器屏幕截图产生相同的结果,然后将最后一个屏幕截图与预期进行比较。

🌐 This function will wait until two consecutive locator screenshots yield the same result, and then compare the last screenshot with the expectation.

用法

const locator = page.getByRole('button');
await expect(locator).toHaveScreenshot('image.png');

请注意,屏幕截图断言仅适用于 Playwright 测试运行程序。

🌐 Note that screenshot assertions only work with Playwright test runner.

参数

  • name string | Array<string>#

    快照名称。

  • options Object (optional)

    • animations "disabled" | "allow" (optional)#

      当设置为 "disabled" 时,会停止 CSS 动画、CSS 过渡和 Web 动画。动画会根据其持续时间得到不同的处理:

      • 有限动画会被快进至完成,因此它们会触发 transitionend 事件。
      • 无限动画被取消到初始状态,然后在屏幕截图后播放。

      默认值为 "disabled",会禁用动画。

    • caret "hide" | "initial" (optional)#

      当设置为 "hide" 时,截图将隐藏文本光标。当设置为 "initial" 时,文本光标的行为不会改变。默认值为 "hide"

    • mask Array<Locator> (optional)#

      指定在截图时应被遮罩的定位器。被遮罩的元素将被一个粉色方框 #FF00FF(可通过 maskColor 自定义)覆盖,完全覆盖其边界框。遮罩也会应用于不可见元素,参见 仅匹配可见元素 可禁用该功能。

    • maskColor string (optional) Added in: v1.35#

      指定被遮罩元素的覆盖框颜色,使用 CSS 颜色格式。默认颜色是粉色 #FF00FF

    • maxDiffPixelRatio number (optional)#

      可接受的不同像素与总像素的比例,介于 01 之间。默认值可通过 TestConfig.expect 配置。默认未设置。

    • maxDiffPixels number (optional)#

      可以不同的像素数量是可接受的。默认值可以通过 TestConfig.expect 配置。默认情况下未设置。

    • omitBackground boolean (optional)#

      隐藏默认的白色背景,并允许捕获带透明度的截屏。不适用于 jpeg 图片。默认值为 false

    • scale "css" | "device" (optional)#

      当设置为 "css" 时,截图将每个页面的 CSS 像素对应一个像素。对于高分辨率设备,这将保持截图文件较小。使用 "device" 选项将每个设备像素对应一个像素,因此高分辨率设备的截图将会大两倍甚至更多。

      默认为 "css"

    • stylePath string | Array<string> (optional) Added in: v1.41#

      包含在截图时要应用的样式表的文件名。在这里,你可以隐藏动态元素,使元素不可见或更改它们的属性,以帮助你创建可重复的截图。该样式表可以穿透 Shadow DOM,并应用于内部框架。

    • threshold number (optional)#

      YIQ 色彩空间中,对比图片中相同像素可接受的感知颜色差异,介于零(严格)到一(宽松)之间,默认值可通过 TestConfig.expect 配置。默认值为 0.2

    • timeout number (optional)#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toHaveScreenshot(options)

Added in: v1.23 locatorAssertions.toHaveScreenshot(options)

此函数将等到两个连续的定位器屏幕截图产生相同的结果,然后将最后一个屏幕截图与预期进行比较。

🌐 This function will wait until two consecutive locator screenshots yield the same result, and then compare the last screenshot with the expectation.

用法

const locator = page.getByRole('button');
await expect(locator).toHaveScreenshot();

请注意,屏幕截图断言仅适用于 Playwright 测试运行程序。

🌐 Note that screenshot assertions only work with Playwright test runner.

参数

  • options Object (optional)
    • animations "disabled" | "allow" (optional)#

      当设置为 "disabled" 时,会停止 CSS 动画、CSS 过渡和 Web 动画。动画会根据其持续时间得到不同的处理:

      • 有限动画会被快进至完成,因此它们会触发 transitionend 事件。
      • 无限动画被取消到初始状态,然后在屏幕截图后播放。

      默认值为 "disabled",会禁用动画。

    • caret "hide" | "initial" (optional)#

      当设置为 "hide" 时,截图将隐藏文本光标。当设置为 "initial" 时,文本光标的行为不会改变。默认值为 "hide"

    • mask Array<Locator> (optional)#

      指定在截图时应被遮罩的定位器。被遮罩的元素将被一个粉色方框 #FF00FF 覆盖(可通过 maskColor 自定义),完全覆盖其边界框。遮罩也会应用到不可见元素,参见 仅匹配可见元素 可禁用此功能。

    • maskColor string (optional) Added in: v1.35#

      指定被遮罩元素的覆盖框颜色,使用 CSS 颜色格式。默认颜色是粉色 #FF00FF

    • maxDiffPixelRatio number (optional)#

      可接受的不同像素与总像素的比例,介于 01 之间。默认值可通过 TestConfig.expect 配置。默认未设置。

    • maxDiffPixels number (optional)#

      可以不同的像素数量是可接受的。默认值可以通过 TestConfig.expect 配置。默认情况下未设置。

    • omitBackground boolean (optional)#

      隐藏默认的白色背景,并允许捕获带透明度的截屏。不适用于 jpeg 图片。默认值为 false

    • scale "css" | "device" (optional)#

      当设置为 "css" 时,截图将每个页面的 CSS 像素对应一个像素。对于高分辨率设备,这将保持截图文件较小。使用 "device" 选项将每个设备像素对应一个像素,因此高分辨率设备的截图将会大两倍甚至更多。

      默认为 "css"

    • stylePath string | Array<string> (optional) Added in: v1.41#

      包含在截图时要应用的样式表的文件名。在这里,你可以隐藏动态元素,使元素不可见或更改它们的属性,以帮助你创建可重复的截图。该样式表可以穿透 Shadow DOM,并应用于内部框架。

    • threshold number (optional)#

      YIQ 色彩空间中,对比图片中相同像素可接受的感知颜色差异,介于零(严格)到一(宽松)之间,默认值可通过 TestConfig.expect 配置。默认值为 0.2

    • timeout number (optional)#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toHaveText

Added in: v1.20 locatorAssertions.toHaveText

确保 Locator 指向具有给定文本的元素。在计算元素的文本内容时,会考虑所有嵌套的元素。你也可以对该值使用正则表达式。

🌐 Ensures the Locator points to an element with the given text. All nested elements will be considered when computing the text content of the element. You can use regular expressions for the value as well.

用法

const locator = page.locator('.title');
await expect(locator).toHaveText(/Welcome, Test User/);
await expect(locator).toHaveText(/Welcome, .*/);

如果你传递一个数组作为期望值,则期望为:

🌐 If you pass an array as an expected value, the expectations are:

  1. 定位器解析为元素列表。
  2. 元素的数量等于数组中期望值的数量。
  3. 列表中的元素具有按顺序一一匹配预期数组值的文本。

例如,考虑以下列表:

🌐 For example, consider the following list:

<ul>
<li>Text 1</li>
<li>Text 2</li>
<li>Text 3</li>
</ul>

让我们看看如何使用断言:

🌐 Let's see how we can use the assertion:

// ✓ Has the right items in the right order
await expect(page.locator('ul > li')).toHaveText(['Text 1', 'Text 2', 'Text 3']);

// ✖ Wrong order
await expect(page.locator('ul > li')).toHaveText(['Text 3', 'Text 2', 'Text 1']);

// ✖ Last item does not match
await expect(page.locator('ul > li')).toHaveText(['Text 1', 'Text 2', 'Text']);

// ✖ Locator points to the outer list element, not to the list items
await expect(page.locator('ul')).toHaveText(['Text 1', 'Text 2', 'Text 3']);

参数

  • expected string | RegExp | Array<string | RegExp> Added in: v1.18#

    预期的字符串或正则表达式或它们的列表。

  • options Object (optional)

    • ignoreCase boolean (optional) Added in: v1.23#

      是否执行不区分大小写的匹配。如果指定,ignoreCase 选项优先于相应的正则表达式标志。

    • timeout number (optional) Added in: v1.18#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

    • useInnerText boolean (optional) Added in: v1.18#

      在获取 DOM 节点文本时,是使用 element.innerText 还是 element.textContent

返回

详情

expected 参数是字符串时,Playwright 会在匹配前对实际文本和预期字符串中的空格和换行进行规范化。当使用正则表达式时,实际文本将按原样进行匹配。

🌐 When expected parameter is a string, Playwright will normalize whitespaces and line breaks both in the actual text and in the expected string before matching. When regular expression is used, the actual text is matched as is.


toHaveValue

Added in: v1.20 locatorAssertions.toHaveValue

确保 Locator 指向具有给定输入值的元素。你也可以为该值使用正则表达式。

🌐 Ensures the Locator points to an element with the given input value. You can use regular expressions for the value as well.

用法

const locator = page.locator('input[type=number]');
await expect(locator).toHaveValue(/[0-9]/);

参数

  • value string | RegExp Added in: v1.18#

    期望值。

  • options Object (optional)

    • timeout number (optional) Added in: v1.18#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toHaveValues

Added in: v1.23 locatorAssertions.toHaveValues

确保 Locator 指向多选/组合框(即带有 multiple 属性的 select),并且选择了指定的值。

🌐 Ensures the Locator points to multi-select/combobox (i.e. a select with the multiple attribute) and the specified values are selected.

用法

例如,给定以下元素:

🌐 For example, given the following element:

<select id="favorite-colors" multiple>
<option value="R">Red</option>
<option value="G">Green</option>
<option value="B">Blue</option>
</select>
const locator = page.locator('id=favorite-colors');
await locator.selectOption(['R', 'G']);
await expect(locator).toHaveValues([/R/, /G/]);

参数

  • values Array<string | RegExp>#

    当前选择的预期选项。

  • options Object (optional)

    • timeout number (optional)#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toMatchAriaSnapshot(expected)

Added in: v1.49 locatorAssertions.toMatchAriaSnapshot(expected)

断言目标元素与给定的辅助功能快照匹配。

🌐 Asserts that the target element matches the given accessibility snapshot.

用法

await page.goto('https://demo.playwright.dev/todomvc/');
await expect(page.locator('body')).toMatchAriaSnapshot(`
- heading "todos"
- textbox "What needs to be done?"
`);

参数

  • expected string#
  • options Object (optional)
    • timeout number (optional)#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


toMatchAriaSnapshot(options)

Added in: v1.50 locatorAssertions.toMatchAriaSnapshot(options)

断言目标元素与给定的辅助功能快照匹配。

🌐 Asserts that the target element matches the given accessibility snapshot.

快照存储在一个单独的 .aria.yml 文件中,位置由配置文件中的 expect.toMatchAriaSnapshot.pathTemplate 和/或 snapshotPathTemplate 属性配置。

🌐 Snapshot is stored in a separate .aria.yml file in a location configured by expect.toMatchAriaSnapshot.pathTemplate and/or snapshotPathTemplate properties in the configuration file.

用法

await expect(page.locator('body')).toMatchAriaSnapshot();
await expect(page.locator('body')).toMatchAriaSnapshot({ name: 'body.aria.yml' });

参数

  • options Object (optional)
    • name string (optional)#

      要存储在与此测试对应的快照文件夹中的快照名称。如果未指定,将生成顺序名称。

    • timeout number (optional)#

      是时候以毫秒为单位重试断言了。TestConfig.expect 中默认为 timeout

返回


属性

🌐 Properties

not

Added in: v1.20 locatorAssertions.not

使断言检查相反的条件。例如,这段代码测试 Locator 不包含文本 "error"

🌐 Makes the assertion check for the opposite condition. For example, this code tests that the Locator doesn't contain text "error":

await expect(locator).not.toContainText('error');

用法

expect(locator).not

类型