LocatorAssertions
LocatorAssertions 类提供了断言方法,可用于在测试中对 Locator 的状态进行断言。
import { test, expect } from '@playwright/test';
test('status becomes submitted', async ({ page }) => {
// ...
await page.getByRole('button').click();
await expect(page.locator('.status')).toHaveText('Submitted');
});
方法
toBeAttached
Added in: v1.33确保Locator指向一个connected到Document或ShadowRoot的元素。
用法
await expect(page.getByText('Hidden text')).toBeAttached();
参数
options
Object (optional)
返回
待检查
Added in: v1.20确保Locator指向一个已勾选的输入框。
用法
const locator = page.getByLabel('Subscribe to newsletter');
await expect(locator).toBeChecked();
参数
options
Object (optional)
返回
toBeDisabled
Added in: v1.20Ensures 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)
返回
toBeEditable
Added in: v1.20确保Locator指向一个可编辑的元素。
用法
const locator = page.getByRole('textbox');
await expect(locator).toBeEditable();
参数
options
Object (optional)
返回
toBeEmpty
Added in: v1.20确保Locator指向一个空的可编辑元素或没有文本的DOM节点。
用法
const locator = page.locator('div.warning');
await expect(locator).toBeEmpty();
参数
options
Object (optional)
返回
toBeEnabled
Added in: v1.20确保Locator指向一个已启用的元素。
用法
const locator = page.locator('button.submit');
await expect(locator).toBeEnabled();
参数
options
Object (optional)
返回
toBeFocused
Added in: v1.20确保 Locator 指向一个获得焦点的 DOM 节点。
用法
const locator = page.getByRole('textbox');
await expect(locator).toBeFocused();
参数
options
Object (optional)
返回
toBeHidden
Added in: v1.20确保Locator要么不解析为任何DOM节点,要么解析为一个不可见的节点。
用法
const locator = page.locator('.my-element');
await expect(locator).toBeHidden();
参数
options
Object (optional)
返回
toBeInViewport
Added in: v1.31确保Locator指向的元素与视口相交,依据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)
返回
toBeVisible
Added in: v1.20要检查列表中至少有一个元素是可见的,请使用 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)
返回
toContainText
Added in: v1.20确保Locator指向包含给定文本的元素。在计算元素的文本内容时,所有嵌套元素都将被考虑在内。您也可以使用正则表达式作为值。
用法
const locator = page.locator('.title');
await expect(locator).toContainText('substring');
await expect(locator).toContainText(/\d messages/);
如果传递一个数组作为期望值,预期条件如下:
- 定位器解析为一组元素。
- 该列表中的部分元素分别包含预期数组中的文本。
- 匹配的元素子集与预期数组的顺序相同。
- 预期数组中的每个文本值都与列表中的某个元素匹配。
例如,考虑以下列表:
<ul>
<li>Item Text 1</li>
<li>Item Text 2</li>
<li>Item Text 3</li>
</ul>
让我们看看如何使用断言:
// ✓ 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> 添加于: v1.18#预期的子字符串或正则表达式或其列表。
-
options
Object (可选)
返回
详情
当expected
参数是字符串时,Playwright会在匹配前对实际文本和预期字符串中的空白字符和换行符进行标准化处理。当使用正则表达式时,实际文本将按原样匹配。
toHaveAccessibleDescription
Added in: v1.44用法
const locator = page.getByTestId('save-button');
await expect(locator).toHaveAccessibleDescription('Save results to disk');
参数
-
预期的无障碍描述。
-
options
Object (可选)-
是否执行不区分大小写的匹配。如果指定了ignoreCase选项,它将优先于相应的正则表达式标志。
-
重试断言的时间,以毫秒为单位。默认为
TestConfig.expect
中的timeout
值。
-
返回
toHaveAccessibleErrorMessage
Added in: v1.50确保Locator指向具有指定aria errormessage的元素。
用法
const locator = page.getByTestId('username-input');
await expect(locator).toHaveAccessibleErrorMessage('Username is required.');
参数
-
预期的可访问错误消息。
-
options
Object (可选)-
是否执行不区分大小写的匹配。如果指定了ignoreCase选项,它将优先于相应的正则表达式标志。
-
重试断言的时间,以毫秒为单位。默认为
TestConfig.expect
中的timeout
值。
-
返回
toHaveAccessibleName
Added in: v1.44确保Locator指向具有给定accessible name的元素。
用法
const locator = page.getByTestId('save-button');
await expect(locator).toHaveAccessibleName('Save to disk');
参数
-
预期的可访问名称。
-
options
Object (可选)-
是否执行不区分大小写的匹配。如果指定了ignoreCase选项,它将优先于相应的正则表达式标志。
-
重试断言的时间,以毫秒为单位。默认为
TestConfig.expect
中的timeout
值。
-
返回
toHaveAttribute(名称, 值)
Added in: v1.20确保Locator指向具有给定属性的元素。
用法
const locator = page.locator('input');
await expect(locator).toHaveAttribute('type', 'text');
参数
-
属性名称。
-
value
string | RegExp 新增于: v1.18#预期的属性值。
-
options
Object (可选)-
ignoreCase
boolean (可选) 添加于: v1.40#是否执行不区分大小写的匹配。如果指定了ignoreCase选项,它将优先于相应的正则表达式标志。
-
timeout
number (可选) 添加于: v1.18#重试断言的时间,以毫秒为单位。默认为
TestConfig.expect
中的timeout
值。
-
返回
toHaveAttribute(名称)
Added in: v1.39确保Locator指向具有给定属性的元素。该方法将断言属性的存在。
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);
参数
-
属性名称。
-
options
Object (可选)
返回
toHaveClass
Added in: v1.20确保Locator指向具有给定CSS类的元素。当提供字符串时,它必须完全匹配元素的class
属性。要匹配单个类或执行部分匹配,请使用正则表达式:
用法
<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|$)/);
当传入一个数组时,该方法会断言定位到的元素列表与预期的类值列表相匹配。每个元素的class属性将与数组中对应的字符串或正则表达式进行匹配:
const locator = page.locator('list > .component');
await expect(locator).toHaveClass(['component', 'component selected', 'component']);
参数
返回
toHaveCount
Added in: v1.20确保Locator解析为确切数量的DOM节点。
用法
const list = page.locator('list > .component');
await expect(list).toHaveCount(3);
参数
-
预期数量。
-
options
Object (可选)
返回
toHaveCSS
Added in: v1.20确保Locator解析为具有指定计算CSS样式的元素。
用法
const locator = page.getByRole('button');
await expect(locator).toHaveCSS('display', 'flex');
参数
返回
拥有ID
Added in: v1.20确保Locator指向具有给定DOM节点ID的元素。
用法
const locator = page.getByRole('textbox');
await expect(locator).toHaveId('lastname');
参数
返回
toHaveJSProperty
Added in: v1.20确保Locator指向具有给定JavaScript属性的元素。请注意,此属性可以是基本类型,也可以是普通的可序列化JavaScript对象。
用法
const locator = page.locator('.component');
await expect(locator).toHaveJSProperty('loaded', true);
参数
-
属性名称。
-
属性值。
-
options
Object (可选)
返回
toHaveRole
Added in: v1.44请注意,角色是作为字符串匹配的,不考虑ARIA角色层次结构。例如,在具有子类角色"switch"
的元素上断言超类角色"checkbox"
将会失败。
用法
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"#必需的aria角色。
-
options
Object (可选)
返回
toHaveScreenshot(名称)
Added in: v1.23该函数将等待直到两个连续的定位器截图产生相同结果,然后将最后一张截图与预期结果进行比较。
用法
const locator = page.getByRole('button');
await expect(locator).toHaveScreenshot('image.png');
请注意,截图断言仅适用于Playwright测试运行器。
参数
-
快照名称。
-
options
Object (可选)-
animations
"disabled" | "allow" (可选)#当设置为
"disabled"
时,会停止CSS动画、CSS过渡和Web动画。动画会根据其持续时间受到不同的处理:- 有限动画会被快进到完成状态,因此会触发
transitionend
事件。 - 无限循环动画会被取消回到初始状态,截图完成后会重新播放。
默认为
"disabled"
表示禁用动画。 - 有限动画会被快进到完成状态,因此会触发
-
caret
"hide" | "initial" (可选)#当设置为
"hide"
时,截图将隐藏文本光标。当设置为"initial"
时,文本光标行为将保持不变。默认为"hide"
。 -
指定截图时应被遮罩的定位器。被遮罩的元素将被完全覆盖其边界框的粉红色盒子
#FF00FF
(可通过maskColor自定义)覆盖。该遮罩也会应用于不可见元素,如需禁用此功能,请参阅Matching only visible elements。 -
maskColor
string (可选) 添加于: v1.35#指定被遮罩元素的覆盖框颜色,使用CSS颜色格式。默认颜色为粉红色
#FF00FF
。 -
maxDiffPixelRatio
number (optional)#可接受的差异像素与总像素之比,范围在
0
到1
之间。默认值可通过TestConfig.expect
配置。默认情况下未设置。 -
允许存在差异的像素数量。默认值可通过
TestConfig.expect
配置。默认情况下未设置。 -
隐藏默认的白色背景,允许捕获带透明度的截图。不适用于
jpeg
图像。默认为false
。 -
scale
"css" | "device" (可选)#当设置为
"css"
时,截图将对应页面上的每个CSS像素生成一个像素。对于高DPI设备,这将保持截图较小。使用"device"
选项将为每个设备像素生成一个像素,因此高DPI设备的截图会是两倍甚至更大。默认为
"css"
。 -
stylePath
string | Array<string> (可选参数) 添加于: v1.41#指定包含样式表的文件名,该样式表将在截图时应用。您可以通过此样式表隐藏动态元素、使元素不可见或更改其属性,以帮助创建可重复的截图。此样式表会穿透Shadow DOM并应用到内部框架。
-
在比较图像中相同像素之间,在YIQ色彩空间中可接受的感知色差,取值范围从零(严格)到一(宽松),默认值可通过
TestConfig.expect
配置。默认为0.2
。 -
重试断言的时间,以毫秒为单位。默认为
TestConfig.expect
中的timeout
值。
-
返回
toHaveScreenshot(选项)
Added in: v1.23该函数将等待直到两个连续的定位器截图产生相同结果,然后将最后一张截图与预期结果进行比较。
用法
const locator = page.getByRole('button');
await expect(locator).toHaveScreenshot();
请注意,截图断言仅适用于Playwright测试运行器。
参数
options
Object (optional)-
animations
"disabled" | "allow" (可选)#当设置为
"disabled"
时,会停止CSS动画、CSS过渡和Web动画。动画会根据其持续时间受到不同的处理:- 有限动画会被快进到完成状态,因此会触发
transitionend
事件。 - 无限循环动画会被取消回到初始状态,截图完成后会重新播放。
默认为
"disabled"
表示禁用动画。 - 有限动画会被快进到完成状态,因此会触发
-
caret
"hide" | "initial" (可选)#当设置为
"hide"
时,截图将隐藏文本光标。当设置为"initial"
时,文本光标行为将保持不变。默认为"hide"
。 -
指定在截图时应被遮罩的定位器。被遮罩的元素将被一个粉红色盒子
#FF00FF
(可通过maskColor自定义)完全覆盖其边界框。该遮罩也会应用于不可见元素,如需禁用此功能,请参阅Matching only visible elements。 -
maskColor
string (可选) 添加于: v1.35#指定被遮罩元素的覆盖框颜色,使用CSS颜色格式。默认颜色为粉红色
#FF00FF
。 -
maxDiffPixelRatio
number (可选)#可接受的差异像素与总像素之比,范围在
0
到1
之间。默认值可通过TestConfig.expect
配置。默认情况下未设置。 -
允许存在差异的像素数量。默认值可通过
TestConfig.expect
配置。默认情况下未设置。 -
隐藏默认的白色背景,允许捕获带透明度的截图。不适用于
jpeg
格式的图片。默认为false
。 -
scale
"css" | "device" (可选)#当设置为
"css"
时,截图将对应页面上的每个CSS像素生成一个像素。对于高DPI设备,这将保持截图较小。使用"device"
选项将为每个设备像素生成一个像素,因此高DPI设备的截图会是两倍甚至更大。默认为
"css"
。 -
stylePath
string | Array<string> (可选) 添加于: v1.41#指定包含样式表的文件名,该样式表将在截图时应用。您可以通过此样式表隐藏动态元素、使元素不可见或更改其属性,以帮助创建可重复的截图。此样式表会穿透Shadow DOM并应用到内部框架。
-
在比较图像中相同像素之间可接受的感知色差,基于YIQ色彩空间,取值范围从零(严格)到一(宽松),默认值可通过
TestConfig.expect
配置。默认为0.2
。 -
重试断言的时间,以毫秒为单位。默认为
TestConfig.expect
中的timeout
值。
-
返回
toHaveText
Added in: v1.20确保Locator指向具有给定文本的元素。在计算元素的文本内容时,所有嵌套元素都将被考虑在内。您也可以使用正则表达式作为值。
用法
const locator = page.locator('.title');
await expect(locator).toHaveText(/Welcome, Test User/);
await expect(locator).toHaveText(/Welcome, .*/);
如果传递一个数组作为期望值,预期条件如下:
- 定位器解析为一组元素。
- 元素数量等于数组中预期值的数量。
- 列表中的元素依次按顺序匹配预期数组值的文本。
例如,考虑以下列表:
<ul>
<li>Text 1</li>
<li>Text 2</li>
<li>Text 3</li>
</ul>
让我们看看如何使用断言:
// ✓ 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> 添加于: v1.18#预期的字符串或正则表达式或它们的列表。
-
options
Object (可选)
返回
详情
当expected
参数是字符串时,Playwright会在匹配前对实际文本和预期字符串中的空白字符和换行符进行标准化处理。当使用正则表达式时,实际文本将按原样匹配。
toHaveValue
Added in: v1.20确保Locator指向具有给定输入值的元素。您也可以对值使用正则表达式。
用法
const locator = page.locator('input[type=number]');
await expect(locator).toHaveValue(/[0-9]/);
参数
返回
toHaveValues
Added in: v1.23确保Locator指向多选/组合框(即带有multiple
属性的select
元素)并选中指定的值。
用法
例如,给定以下元素:
<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/]);
参数
返回
toMatchAriaSnapshot(expected)
Added in: v1.49断言目标元素与给定的无障碍快照匹配。
用法
await page.goto('https://demo.playwright.dev/todomvc/');
await expect(page.locator('body')).toMatchAriaSnapshot(`
- heading "todos"
- textbox "What needs to be done?"
`);
参数
返回
toMatchAriaSnapshot(options)
Added in: v1.50断言目标元素与给定的无障碍快照匹配。
快照存储在单独的.aria.yml
文件中,位置由配置文件中的expect.toMatchAriaSnapshot.pathTemplate
和/或snapshotPathTemplate
属性配置。
用法
await expect(page.locator('body')).toMatchAriaSnapshot();
await expect(page.locator('body')).toMatchAriaSnapshot({ name: 'body.aria.yml' });
参数
options
Object (optional)
返回
属性
不
Added in: v1.20使断言检查相反的条件。例如,以下代码测试定位器不包含文本"error"
:
await expect(locator).not.toContainText('error');
用法
expect(locator).not
类型