LocatorAssertions
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.33Ensures that Locator points to an element that is connected to a Document or a ShadowRoot.
Usage
await expect(page.getByText('Hidden text')).toBeAttached();
Arguments
options
Object (optional)
Returns
toBeChecked
Added in: v1.20Ensures the Locator points to a checked input.
Usage
const locator = page.getByLabel('Subscribe to newsletter');
await expect(locator).toBeChecked();
Arguments
options
Object (optional)
Returns
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.
Usage
const locator = page.locator('button.submit');
await expect(locator).toBeDisabled();
Arguments
options
Object (optional)
Returns
toBeEditable
Added in: v1.20Ensures the Locator points to an editable element.
Usage
const locator = page.getByRole('textbox');
await expect(locator).toBeEditable();
Arguments
options
Object (optional)
Returns
toBeEmpty
Added in: v1.20Ensures 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
options
Object (optional)
Returns
toBeEnabled
Added in: v1.20Ensures the Locator points to an enabled element.
Usage
const locator = page.locator('button.submit');
await expect(locator).toBeEnabled();
Arguments
options
Object (optional)
Returns
toBeFocused
Added in: v1.20Ensures the Locator points to a focused DOM node.
Usage
const locator = page.getByRole('textbox');
await expect(locator).toBeFocused();
Arguments
options
Object (optional)
Returns
toBeHidden
Added in: v1.20Ensures 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
options
Object (optional)
Returns
toBeInViewport
Added in: v1.31Ensures 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
options
Object (optional)
Returns
toBeVisible
Added in: v1.20Ensures that Locator points to an attached and visible DOM node.
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
options
Object (optional)
Returns
toContainText
Added in: v1.20Ensures 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
string | RegExp | Array<string | RegExp> Added in: v1.18#Expected substring or RegExp or a list of those.
-
options
Object (optional)-
ignoreCase
boolean (optional) Added in: v1.23#Whether to perform case-insensitive match.
ignoreCase
option takes precedence over the corresponding regular expression flag if specified. -
timeout
number (optional) Added in: v1.18#Time to retry the assertion for in milliseconds. Defaults to
timeout
inTestConfig.expect
. -
useInnerText
boolean (optional) Added in: v1.18#Whether to use
element.innerText
instead ofelement.textContent
when retrieving DOM node text.
-
Returns
Details
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.44Ensures 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.
-
options
Object (optional)
Returns
toHaveAccessibleName
Added in: v1.44Ensures 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.
-
options
Object (optional)
Returns
toHaveAttribute(name, value)
Added in: v1.20Ensures the Locator points to an element with given attribute.
Usage
const locator = page.locator('input');
await expect(locator).toHaveAttribute('type', 'text');
Arguments
-
Attribute name.
-
value
string | RegExp Added in: v1.18#Expected attribute value.
-
options
Object (optional)-
ignoreCase
boolean (optional) Added in: v1.40#Whether to perform case-insensitive match.
ignoreCase
option takes precedence over the corresponding regular expression flag if specified. -
timeout
number (optional) Added in: v1.18#Time to retry the assertion for in milliseconds. Defaults to
timeout
inTestConfig.expect
.
-
Returns
toHaveAttribute(name)
Added in: v1.39Ensures 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.
-
options
Object (optional)
Returns
toHaveClass
Added in: v1.20Ensures 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
-
expected
string | RegExp | Array<string | RegExp> Added in: v1.18#Expected class or RegExp or a list of those.
-
options
Object (optional)
Returns
toHaveCount
Added in: v1.20Ensures 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.
-
options
Object (optional)
Returns
toHaveCSS
Added in: v1.20Ensures 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 property name.
-
value
string | RegExp Added in: v1.18#CSS property value.
-
options
Object (optional)
Returns
toHaveId
Added in: v1.20Ensures the Locator points to an element with the given DOM Node ID.
Usage
const locator = page.getByRole('textbox');
await expect(locator).toHaveId('lastname');
Arguments
Returns
toHaveJSProperty
Added in: v1.20Ensures 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.
-
options
Object (optional)
Returns
toHaveRole
Added in: v1.44Ensures the Locator points to an element with a given ARIA role.
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.
-
options
Object (optional)
Returns
toHaveScreenshot(name)
Added in: v1.23This 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');
Note that screenshot assertions only work with Playwright test runner.
Arguments
-
Snapshot name.
-
options
Object (optional)-
animations
"disabled" | "allow" (optional)#When set to
"disabled"
, stops CSS animations, CSS transitions and Web Animations. Animations get different treatment depending on their duration:- 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.
Defaults to
"disabled"
that disables animations. - finite animations are fast-forwarded to completion, so they'll fire
-
caret
"hide" | "initial" (optional)#When set to
"hide"
, screenshot will hide text caret. When set to"initial"
, text caret behavior will not be changed. Defaults to"hide"
. -
mask
Array<Locator> (optional)#Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink box
#FF00FF
(customized bymaskColor
) that completely covers its bounding box. -
maskColor
string (optional) Added in: v1.35#Specify the color of the overlay box for masked elements, in CSS color format. Default color is pink
#FF00FF
. -
maxDiffPixelRatio
number (optional)#An acceptable ratio of pixels that are different to the total amount of pixels, between
0
and1
. Default is configurable withTestConfig.expect
. Unset by default. -
maxDiffPixels
number (optional)#An acceptable amount of pixels that could be different. Default is configurable with
TestConfig.expect
. Unset by default. -
omitBackground
boolean (optional)#Hides default white background and allows capturing screenshots with transparency. Not applicable to
jpeg
images. Defaults tofalse
. -
scale
"css" | "device" (optional)#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.Defaults to
"css"
. -
stylePath
string | Array<string> (optional) Added in: v1.41#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.
-
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 to0.2
. -
Time to retry the assertion for in milliseconds. Defaults to
timeout
inTestConfig.expect
.
-
Returns
toHaveScreenshot()
Added in: v1.23This 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();
Note that screenshot assertions only work with Playwright test runner.
Arguments
options
Object (optional)-
animations
"disabled" | "allow" (optional)#When set to
"disabled"
, stops CSS animations, CSS transitions and Web Animations. Animations get different treatment depending on their duration:- 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.
Defaults to
"disabled"
that disables animations. - finite animations are fast-forwarded to completion, so they'll fire
-
caret
"hide" | "initial" (optional)#When set to
"hide"
, screenshot will hide text caret. When set to"initial"
, text caret behavior will not be changed. Defaults to"hide"
. -
mask
Array<Locator> (optional)#Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink box
#FF00FF
(customized bymaskColor
) that completely covers its bounding box. -
maskColor
string (optional) Added in: v1.35#Specify the color of the overlay box for masked elements, in CSS color format. Default color is pink
#FF00FF
. -
maxDiffPixelRatio
number (optional)#An acceptable ratio of pixels that are different to the total amount of pixels, between
0
and1
. Default is configurable withTestConfig.expect
. Unset by default. -
maxDiffPixels
number (optional)#An acceptable amount of pixels that could be different. Default is configurable with
TestConfig.expect
. Unset by default. -
omitBackground
boolean (optional)#Hides default white background and allows capturing screenshots with transparency. Not applicable to
jpeg
images. Defaults tofalse
. -
scale
"css" | "device" (optional)#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.Defaults to
"css"
. -
stylePath
string | Array<string> (optional) Added in: v1.41#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.
-
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 to0.2
. -
Time to retry the assertion for in milliseconds. Defaults to
timeout
inTestConfig.expect
.
-
Returns