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确保 Locator 指向 connected 指向 Document 或 ShadowRoot 的元素。
¥Ensures that Locator points to an element that is connected to a Document or a ShadowRoot.
用法
¥Usage
await expect(page.getByText('Hidden text')).toBeAttached();
参数
¥Arguments
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
toBeChecked
Added in: v1.20确保 Locator 指向已检查的输入。
¥Ensures the Locator points to a checked input.
用法
¥Usage
const locator = page.getByLabel('Subscribe to newsletter');
await expect(locator).toBeChecked();
参数
¥Arguments
-
options
Object (optional)
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
toBeDisabled
Added in: v1.20确保 Locator 指向禁用的元素。如果元素具有 "disabled" 属性或通过 'aria-disabled' 禁用,则该元素将被禁用。请注意,只有 HTML button
、input
、select
、textarea
、option
、optgroup
等原生控制元素可以通过设置 "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.
用法
¥Usage
const locator = page.locator('button.submit');
await expect(locator).toBeDisabled();
参数
¥Arguments
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
toBeEditable
Added in: v1.20确保 Locator 指向可编辑元素。
¥Ensures the Locator points to an editable element.
用法
¥Usage
const locator = page.getByRole('textbox');
await expect(locator).toBeEditable();
参数
¥Arguments
-
options
Object (optional)
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
toBeEmpty
Added in: v1.20确保 Locator 指向空的可编辑元素或没有文本的 DOM 节点。
¥Ensures the Locator points to an empty editable element or to a DOM node that has no text.
用法
¥Usage
const locator = page.locator('div.warning');
await expect(locator).toBeEmpty();
参数
¥Arguments
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
toBeEnabled
Added in: v1.20确保 Locator 指向启用的元素。
¥Ensures the Locator points to an enabled element.
用法
¥Usage
const locator = page.locator('button.submit');
await expect(locator).toBeEnabled();
参数
¥Arguments
-
options
Object (optional)
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
toBeFocused
Added in: v1.20确保 Locator 指向焦点 DOM 节点。
¥Ensures the Locator points to a focused DOM node.
用法
¥Usage
const locator = page.getByRole('textbox');
await expect(locator).toBeFocused();
参数
¥Arguments
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
toBeHidden
Added in: v1.20确保 Locator 不解析为任何 DOM 节点,或者解析为 non-visible 节点。
¥Ensures that Locator either does not resolve to any DOM node, or resolves to a non-visible one.
用法
¥Usage
const locator = page.locator('.my-element');
await expect(locator).toBeHidden();
参数
¥Arguments
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
toBeInViewport
Added in: v1.31根据 交集监视器 API,确保 Locator 指向与视口相交的元素。
¥Ensures the Locator points to an element that intersects viewport, according to the intersection observer API.
用法
¥Usage
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 });
参数
¥Arguments
元素与相交视口的最小比率。如果等于 0
,则元素应以任意正比率与视口相交。默认为 0
。
¥The minimal ratio of the element to intersect viewport. If equals to 0
, then element should intersect viewport at any positive ratio. Defaults to 0
.
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
toBeVisible
Added in: v1.20确保 Locator 指向附加的 visible 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().
用法
¥Usage
// 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();
参数
¥Arguments
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
toContainText
Added in: v1.20确保 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.
用法
¥Usage
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:
-
定位器解析为元素列表。
¥Locator resolves to a list of elements.
-
该列表子集中的元素分别包含预期数组中的文本。
¥Elements from a subset of this list contain text from the expected array, respectively.
-
匹配的元素子集与预期数组具有相同的顺序。
¥The matching subset of elements has the same order as the expected array.
-
预期数组中的每个文本值都与列表中的某个元素匹配。
¥Each text value from the expected array is matched by some element from the list.
例如,考虑以下列表:
¥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']);
参数
¥Arguments
预期的子字符串或正则表达式或这些的列表。
¥Expected substring or RegExp or a list of those.
是否进行不区分大小写的匹配。如果指定,ignoreCase 选项优先于相应的正则表达式标志。
¥Whether to perform case-insensitive match. ignoreCase option takes precedence over the corresponding regular expression flag if specified.
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
检索 DOM 节点文本时是否使用 element.innerText
而不是 element.textContent
。
¥Whether to use element.innerText
instead of element.textContent
when retrieving DOM node text.
返回
¥Returns
细节
¥Details
当 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¥Ensures the Locator points to an element with a given accessible description.
用法
¥Usage
const locator = page.getByTestId('save-button');
await expect(locator).toHaveAccessibleDescription('Save results to disk');
参数
¥Arguments
预期可访问描述。
¥Expected accessible description.
是否进行不区分大小写的匹配。如果指定,ignoreCase 选项优先于相应的正则表达式标志。
¥Whether to perform case-insensitive match. ignoreCase option takes precedence over the corresponding regular expression flag if specified.
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
toHaveAccessibleName
Added in: v1.44¥Ensures the Locator points to an element with a given accessible name.
用法
¥Usage
const locator = page.getByTestId('save-button');
await expect(locator).toHaveAccessibleName('Save to disk');
参数
¥Arguments
预期可访问名称。
¥Expected accessible name.
是否进行不区分大小写的匹配。如果指定,ignoreCase 选项优先于相应的正则表达式标志。
¥Whether to perform case-insensitive match. ignoreCase option takes precedence over the corresponding regular expression flag if specified.
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
toHaveAttribute(name, value)
Added in: v1.20确保 Locator 指向具有给定属性的元素。
¥Ensures the Locator points to an element with given attribute.
用法
¥Usage
const locator = page.locator('input');
await expect(locator).toHaveAttribute('type', 'text');
参数
¥Arguments
属性名称。
¥Attribute name.
期望的属性值。
¥Expected attribute value.
是否进行不区分大小写的匹配。如果指定,ignoreCase 选项优先于相应的正则表达式标志。
¥Whether to perform case-insensitive match. ignoreCase option takes precedence over the corresponding regular expression flag if specified.
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
toHaveAttribute(name)
Added in: v1.39确保 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');
用法
¥Usage
await expect(locator).toHaveAttribute(name);
await expect(locator).toHaveAttribute(name, options);
参数
¥Arguments
属性名称。
¥Attribute name.
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
toHaveClass
Added in: v1.20确保 Locator 指向具有给定 CSS 类的元素。这需要是完全匹配或使用宽松的正则表达式。
¥Ensures the Locator points to an element with given CSS classes. This needs to be a full match or using a relaxed regular expression.
用法
¥Usage
<div class='selected row' id='component'></div>
const locator = page.locator('#component');
await expect(locator).toHaveClass(/selected/);
await expect(locator).toHaveClass('selected row');
请注意,如果数组作为预期值传递,则可以断言整个元素列表:
¥Note that if array is passed as an expected value, entire lists of elements can be asserted:
const locator = page.locator('list > .component');
await expect(locator).toHaveClass(['component', 'component selected', 'component']);
参数
¥Arguments
预期的类或 RegExp 或这些的列表。
¥Expected class or RegExp or a list of those.
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
toHaveCount
Added in: v1.20确保 Locator 解析为确切数量的 DOM 节点。
¥Ensures the Locator resolves to an exact number of DOM nodes.
用法
¥Usage
const list = page.locator('list > .component');
await expect(list).toHaveCount(3);
参数
¥Arguments
预期计数。
¥Expected count.
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
toHaveCSS
Added in: v1.20确保 Locator 解析为具有给定计算 CSS 样式的元素。
¥Ensures the Locator resolves to an element with the given computed CSS style.
用法
¥Usage
const locator = page.getByRole('button');
await expect(locator).toHaveCSS('display', 'flex');
参数
¥Arguments
CSS 属性名称。
¥CSS property name.
CSS 属性值。
¥CSS property value.
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
toHaveId
Added in: v1.20确保 Locator 指向具有给定 DOM 节点 ID 的元素。
¥Ensures the Locator points to an element with the given DOM Node ID.
用法
¥Usage
const locator = page.getByRole('textbox');
await expect(locator).toHaveId('lastname');
参数
¥Arguments
元素 ID。
¥Element id.
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
toHaveJSProperty
Added in: v1.20确保 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.
用法
¥Usage
const locator = page.locator('.component');
await expect(locator).toHaveJSProperty('loaded', true);
参数
¥Arguments
属性名称。
¥Property name.
属性值
¥Property value.
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
toHaveRole
Added in: v1.44确保 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.
用法
¥Usage
const locator = page.getByTestId('save-button');
await expect(locator).toHaveRole('button');
参数
¥Arguments
-
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"#所需的咏叹调角色。
¥Required aria role.
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
toHaveScreenshot(name)
Added in: v1.23此函数将等到两个连续的定位器屏幕截图产生相同的结果,然后将最后一个屏幕截图与预期进行比较。
¥This function will wait until two consecutive locator screenshots yield the same result, and then compare the last screenshot with the expectation.
用法
¥Usage
const locator = page.getByRole('button');
await expect(locator).toHaveScreenshot('image.png');
请注意,屏幕截图断言仅适用于 Playwright 测试运行程序。
¥Note that screenshot assertions only work with Playwright test runner.
参数
¥Arguments
快照名称。
¥Snapshot name.
options
Object (optional)
-
animations
"disabled" | "allow"(可选)#¥
animations
"disabled" | "allow" (optional)#当设置为
"disabled"
时,停止 CSS 动画、CSS 转场和 Web 动画。动画根据其持续时间得到不同的处理:¥When set to
"disabled"
, stops CSS animations, CSS transitions and Web Animations. Animations get different treatment depending on their duration:-
有限动画会快进完成,因此它们会触发
transitionend
事件。¥finite animations are fast-forwarded to completion, so they'll fire
transitionend
event. -
无限动画被取消到初始状态,然后在屏幕截图后播放。
¥infinite animations are canceled to initial state, and then played over after the screenshot.
默认为
"disabled"
,禁用动画。¥Defaults to
"disabled"
that disables animations. -
-
caret
"hide" | "initial"(可选)#¥
caret
"hide" | "initial" (optional)#当设置为
"hide"
时,屏幕截图将隐藏文本插入符。当设置为"initial"
时,文本插入符行为将不会更改。默认为"hide"
。¥When set to
"hide"
, screenshot will hide text caret. When set to"initial"
, text caret behavior will not be changed. Defaults to"hide"
.
指定截取屏幕截图时应屏蔽的定位器。被遮罩的元素将被一个粉色框 #FF00FF
(由 maskColor 定制)覆盖,完全覆盖其边界框。
¥Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink box #FF00FF
(customized by maskColor) that completely covers its bounding box.
指定屏蔽元素的覆盖框的颜色,以 CSS 颜色格式 为单位。默认颜色为粉色 #FF00FF
。
¥Specify the color of the overlay box for masked elements, in CSS color format. Default color is pink #FF00FF
.
可接受的不同于像素总数的像素比例,介于 0
和 1
之间。默认值可通过 TestConfig.expect
配置。默认情况下取消设置。
¥An acceptable ratio of pixels that are different to the total amount of pixels, between 0
and 1
. Default is configurable with TestConfig.expect
. Unset by default.
可接受的像素数量,可能有所不同。默认值可通过 TestConfig.expect
配置。默认情况下取消设置。
¥An acceptable amount of pixels that could be different. Default is configurable with TestConfig.expect
. Unset by default.
隐藏默认的白色背景并允许捕获透明的屏幕截图。不适用于 jpeg
图片。默认为 false
。
¥Hides default white background and allows capturing screenshots with transparency. Not applicable to jpeg
images. Defaults to false
.
-
scale
"css" | "device"(可选)#¥
scale
"css" | "device" (optional)#当设置为
"css"
时,屏幕截图页面上的每个 css 像素将有一个像素。对于高 dpi 设备,这将使屏幕截图保持较小。使用"device"
选项将为每个设备像素生成一个像素,因此高 dpi 设备的屏幕截图将是原来的两倍甚至更大。¥When set to
"css"
, screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this will keep screenshots small. Using"device"
option will produce a single pixel per each device pixel, so screenshots of high-dpi devices will be twice as large or even larger.默认为
"css"
。¥Defaults to
"css"
.
包含制作屏幕截图时要应用的样式表的文件名。你可以在此处隐藏动态元素、使元素不可见或更改其属性以帮助你创建可重复的屏幕截图。该样式表穿透 Shadow DOM 并应用于内部框架。
¥File name containing the stylesheet to apply while making the screenshot. This is where you can hide dynamic elements, make elements invisible or change their properties to help you creating repeatable screenshots. This stylesheet pierces the Shadow DOM and applies to the inner frames.
比较图片中相同像素之间可接受的 YIQ 色彩空间 感知色差,介于零(严格)和一(宽松)之间,默认值可通过 TestConfig.expect
配置。默认为 0.2
。
¥An acceptable perceived color difference in the YIQ color space between the same pixel in compared images, between zero (strict) and one (lax), default is configurable with TestConfig.expect
. Defaults to 0.2
.
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
toHaveScreenshot()
Added in: v1.23此函数将等到两个连续的定位器屏幕截图产生相同的结果,然后将最后一个屏幕截图与预期进行比较。
¥This function will wait until two consecutive locator screenshots yield the same result, and then compare the last screenshot with the expectation.
用法
¥Usage
const locator = page.getByRole('button');
await expect(locator).toHaveScreenshot();
请注意,屏幕截图断言仅适用于 Playwright 测试运行程序。
¥Note that screenshot assertions only work with Playwright test runner.
参数
¥Arguments
options
Object (optional)
-
animations
"disabled" | "allow"(可选)#¥
animations
"disabled" | "allow" (optional)#当设置为
"disabled"
时,停止 CSS 动画、CSS 转场和 Web 动画。动画根据其持续时间得到不同的处理:¥When set to
"disabled"
, stops CSS animations, CSS transitions and Web Animations. Animations get different treatment depending on their duration:-
有限动画会快进完成,因此它们会触发
transitionend
事件。¥finite animations are fast-forwarded to completion, so they'll fire
transitionend
event. -
无限动画被取消到初始状态,然后在屏幕截图后播放。
¥infinite animations are canceled to initial state, and then played over after the screenshot.
默认为
"disabled"
,禁用动画。¥Defaults to
"disabled"
that disables animations. -
-
caret
"hide" | "initial"(可选)#¥
caret
"hide" | "initial" (optional)#当设置为
"hide"
时,屏幕截图将隐藏文本插入符。当设置为"initial"
时,文本插入符行为将不会更改。默认为"hide"
。¥When set to
"hide"
, screenshot will hide text caret. When set to"initial"
, text caret behavior will not be changed. Defaults to"hide"
.
指定截取屏幕截图时应屏蔽的定位器。被遮罩的元素将被一个粉色框 #FF00FF
(由 maskColor 定制)覆盖,完全覆盖其边界框。
¥Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink box #FF00FF
(customized by maskColor) that completely covers its bounding box.
指定屏蔽元素的覆盖框的颜色,以 CSS 颜色格式 为单位。默认颜色为粉色 #FF00FF
。
¥Specify the color of the overlay box for masked elements, in CSS color format. Default color is pink #FF00FF
.
可接受的不同于像素总数的像素比例,介于 0
和 1
之间。默认值可通过 TestConfig.expect
配置。默认情况下取消设置。
¥An acceptable ratio of pixels that are different to the total amount of pixels, between 0
and 1
. Default is configurable with TestConfig.expect
. Unset by default.
可接受的像素数量,可能有所不同。默认值可通过 TestConfig.expect
配置。默认情况下取消设置。
¥An acceptable amount of pixels that could be different. Default is configurable with TestConfig.expect
. Unset by default.
隐藏默认的白色背景并允许捕获透明的屏幕截图。不适用于 jpeg
图片。默认为 false
。
¥Hides default white background and allows capturing screenshots with transparency. Not applicable to jpeg
images. Defaults to false
.
-
scale
"css" | "device"(可选)#¥
scale
"css" | "device" (optional)#当设置为
"css"
时,屏幕截图页面上的每个 css 像素将有一个像素。对于高 dpi 设备,这将使屏幕截图保持较小。使用"device"
选项将为每个设备像素生成一个像素,因此高 dpi 设备的屏幕截图将是原来的两倍甚至更大。¥When set to
"css"
, screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this will keep screenshots small. Using"device"
option will produce a single pixel per each device pixel, so screenshots of high-dpi devices will be twice as large or even larger.默认为
"css"
。¥Defaults to
"css"
.
包含制作屏幕截图时要应用的样式表的文件名。你可以在此处隐藏动态元素、使元素不可见或更改其属性以帮助你创建可重复的屏幕截图。该样式表穿透 Shadow DOM 并应用于内部框架。
¥File name containing the stylesheet to apply while making the screenshot. This is where you can hide dynamic elements, make elements invisible or change their properties to help you creating repeatable screenshots. This stylesheet pierces the Shadow DOM and applies to the inner frames.
比较图片中相同像素之间可接受的 YIQ 色彩空间 感知色差,介于零(严格)和一(宽松)之间,默认值可通过 TestConfig.expect
配置。默认为 0.2
。
¥An acceptable perceived color difference in the YIQ color space between the same pixel in compared images, between zero (strict) and one (lax), default is configurable with TestConfig.expect
. Defaults to 0.2
.
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
toHaveText
Added in: v1.20确保 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.
用法
¥Usage
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:
-
定位器解析为元素列表。
¥Locator resolves to a list of elements.
-
元素的数量等于数组中期望值的数量。
¥The number of elements equals the number of expected values in the array.
-
列表中的元素具有按顺序一一匹配预期数组值的文本。
¥Elements from the list have text matching expected array values, one by one, in order.
例如,考虑以下列表:
¥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']);
参数
¥Arguments
预期的字符串或正则表达式或它们的列表。
¥Expected string or RegExp or a list of those.
是否进行不区分大小写的匹配。如果指定,ignoreCase 选项优先于相应的正则表达式标志。
¥Whether to perform case-insensitive match. ignoreCase option takes precedence over the corresponding regular expression flag if specified.
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
检索 DOM 节点文本时是否使用 element.innerText
而不是 element.textContent
。
¥Whether to use element.innerText
instead of element.textContent
when retrieving DOM node text.
返回
¥Returns
细节
¥Details
当 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确保 Locator 指向具有给定输入值的元素。你也可以使用正则表达式作为值。
¥Ensures the Locator points to an element with the given input value. You can use regular expressions for the value as well.
用法
¥Usage
const locator = page.locator('input[type=number]');
await expect(locator).toHaveValue(/[0-9]/);
参数
¥Arguments
期望值。
¥Expected value.
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
toHaveValues
Added in: v1.23确保 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.
用法
¥Usage
例如,给定以下元素:
¥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/]);
参数
¥Arguments
当前选择的预期选项。
¥Expected options currently selected.
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
toMatchAriaSnapshot
Added in: v1.49断言目标元素与给定的 可访问性快照 匹配。
¥Asserts that the target element matches the given accessibility snapshot.
用法
¥Usage
await page.goto('https://demo.playwright.dev/todomvc/');
await expect(page.locator('body')).toMatchAriaSnapshot(`
- heading "todos"
- textbox "What needs to be done?"
`);
参数
¥Arguments
重试断言的时间(以毫秒为单位)。默认为 TestConfig.expect
中的 timeout
。
¥Time to retry the assertion for in milliseconds. Defaults to timeout
in TestConfig.expect
.
返回
¥Returns
属性
¥Properties
not
Added in: v1.20使断言检查相反的条件。例如,此代码测试定位器不包含文本 "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');
用法
¥Usage
expect(locator).not
类型
¥Type