LocatorAssertions
The LocatorAssertions class provides assertion methods that can be used to make assertions about the Locator state in the tests.
// ...
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
public class TestLocator {
// ...
@Test
void statusBecomesSubmitted() {
// ...
page.getByRole(AriaRole.BUTTON).click();
assertThat(page.locator(".status")).hasText("Submitted");
}
}
方法 (Methods)
containsClass
Added in: v1.52Ensures 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>
assertThat(page.locator("#component")).containsClass("middle selected row");
assertThat(page.locator("#component")).containsClass("selected");
assertThat(page.locator("#component")).containsClass("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>
assertThat(page.locator(".list > .component")).containsClass(new String[] {"inactive", "active", "inactive"});
參數
-
expected
String | List<String>#A string containing expected class names, separated by spaces, or a list of such strings to assert multiple elements.
-
options
LocatorAssertions.ContainsClassOptions
(optional)
傳回值
containsText
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.
使用方式
assertThat(page.locator(".title")).containsText("substring");
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
assertThat(page.locator("ul > li")).containsText(new String[] {"Text 1", "Text 3", "Text 4"});
// ✖ Wrong order
assertThat(page.locator("ul > li")).containsText(new String[] {"Text 3", "Text 2"});
// ✖ No item contains this text
assertThat(page.locator("ul > li")).containsText(new String[] {"Some 33"});
// ✖ Locator points to the outer list element, not to the list items
assertThat(page.locator("ul")).containsText(new String[] {"Text 3"});
參數
-
expected
String | Pattern | String[] | Pattern[] Added in: v1.18#Expected substring or RegExp or a list of those.
-
options
LocatorAssertions.ContainsTextOptions
(optional)-
setIgnoreCase
boolean (optional) Added in: v1.23#Whether to perform case-insensitive match. setIgnoreCase option takes precedence over the corresponding regular expression flag if specified.
-
setTimeout
double (optional) Added in: v1.18#Time to retry the assertion for in milliseconds. Defaults to
5000
. -
setUseInnerText
boolean (optional) Added in: v1.18#Whether to use
element.innerText
instead ofelement.textContent
when retrieving DOM node text.
-
傳回值
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.
hasAccessibleDescription
Added in: v1.44Ensures the Locator points to an element with a given accessible description.
使用方式
Locator locator = page.getByTestId("save-button");
assertThat(locator).hasAccessibleDescription("Save results to disk");
參數
-
Expected accessible description.
-
options
LocatorAssertions.HasAccessibleDescriptionOptions
(optional)-
setIgnoreCase
boolean (optional)#Whether to perform case-insensitive match. setIgnoreCase option takes precedence over the corresponding regular expression flag if specified.
-
Time to retry the assertion for in milliseconds. Defaults to
5000
.
-
傳回值
hasAccessibleErrorMessage
Added in: v1.50Ensures the Locator points to an element with a given aria errormessage.
使用方式
Locator locator = page.getByTestId("username-input");
assertThat(locator).hasAccessibleErrorMessage("Username is required.");
參數
-
errorMessage
String | Pattern#Expected accessible error message.
-
options
LocatorAssertions.HasAccessibleErrorMessageOptions
(optional)-
setIgnoreCase
boolean (optional)#Whether to perform case-insensitive match. setIgnoreCase option takes precedence over the corresponding regular expression flag if specified.
-
Time to retry the assertion for in milliseconds. Defaults to
5000
.
-
傳回值
hasAccessibleName
Added in: v1.44Ensures the Locator points to an element with a given accessible name.
使用方式
Locator locator = page.getByTestId("save-button");
assertThat(locator).hasAccessibleName("Save to disk");
參數
-
Expected accessible name.
-
options
LocatorAssertions.HasAccessibleNameOptions
(optional)-
setIgnoreCase
boolean (optional)#Whether to perform case-insensitive match. setIgnoreCase option takes precedence over the corresponding regular expression flag if specified.
-
Time to retry the assertion for in milliseconds. Defaults to
5000
.
-
傳回值
hasAttribute
Added in: v1.20Ensures the Locator points to an element with given attribute.
使用方式
assertThat(page.locator("input")).hasAttribute("type", "text");
參數
-
Attribute name.
-
value
String | Pattern Added in: v1.18#Expected attribute value.
-
options
LocatorAssertions.HasAttributeOptions
(optional)-
setIgnoreCase
boolean (optional) Added in: v1.40#Whether to perform case-insensitive match. setIgnoreCase option takes precedence over the corresponding regular expression flag if specified.
-
setTimeout
double (optional) Added in: v1.18#Time to retry the assertion for in milliseconds. Defaults to
5000
.
-
傳回值
hasClass
Added in: v1.20Ensures 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 assertThat(locator).containsClass().
使用方式
<div class='middle selected row' id='component'></div>
assertThat(page.locator("#component")).hasClass("middle selected row");
assertThat(page.locator("#component")).hasClass(Pattern.compile("(^|\\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:
assertThat(page.locator(".list > .component")).hasClass(new String[] {"component", "component selected", "component"});
參數
-
expected
String | Pattern | String[] | Pattern[] Added in: v1.18#Expected class or RegExp or a list of those.
-
options
LocatorAssertions.HasClassOptions
(optional)
傳回值
hasCount
Added in: v1.20Ensures the Locator resolves to an exact number of DOM nodes.
使用方式
assertThat(page.locator("list > .component")).hasCount(3);
參數
-
Expected count.
-
options
LocatorAssertions.HasCountOptions
(optional)
傳回值
hasCSS
Added in: v1.20Ensures the Locator resolves to an element with the given computed CSS style.
使用方式
assertThat(page.getByRole(AriaRole.BUTTON)).hasCSS("display", "flex");
參數
-
CSS property name.
-
value
String | Pattern Added in: v1.18#CSS property value.
-
options
LocatorAssertions.HasCSSOptions
(optional)
傳回值
hasId
Added in: v1.20Ensures the Locator points to an element with the given DOM Node ID.
使用方式
assertThat(page.getByRole(AriaRole.TEXTBOX)).hasId("lastname");
參數
傳回值
hasJSProperty
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.
使用方式
assertThat(page.locator("input")).hasJSProperty("loaded", true);
參數
-
Property name.
-
Property value.
-
options
LocatorAssertions.HasJSPropertyOptions
(optional)
傳回值
hasRole
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.
使用方式
Locator locator = page.getByTestId("save-button");
assertThat(locator).hasRole(AriaRole.BUTTON);
參數
-
role
enum AriaRole { 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
LocatorAssertions.HasRoleOptions
(optional)
傳回值
hasText
Added in: v1.20Ensures 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.
使用方式
assertThat(page.locator(".title")).hasText("Welcome, Test User");
assertThat(page.locator(".title")).hasText(Pattern.compile("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
assertThat(page.locator("ul > li")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
// ✖ Wrong order
assertThat(page.locator("ul > li")).hasText(new String[] {"Text 3", "Text 2", "Text 1"});
// ✖ Last item does not match
assertThat(page.locator("ul > li")).hasText(new String[] {"Text 1", "Text 2", "Text"});
// ✖ Locator points to the outer list element, not to the list items
assertThat(page.locator("ul")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
參數
-
expected
String | Pattern | String[] | Pattern[] Added in: v1.18#Expected string or RegExp or a list of those.
-
options
LocatorAssertions.HasTextOptions
(optional)-
setIgnoreCase
boolean (optional) Added in: v1.23#Whether to perform case-insensitive match. setIgnoreCase option takes precedence over the corresponding regular expression flag if specified.
-
setTimeout
double (optional) Added in: v1.18#Time to retry the assertion for in milliseconds. Defaults to
5000
. -
setUseInnerText
boolean (optional) Added in: v1.18#Whether to use
element.innerText
instead ofelement.textContent
when retrieving DOM node text.
-
傳回值
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.
hasValue
Added in: v1.20Ensures the Locator points to an element with the given input value. You can use regular expressions for the value as well.
使用方式
assertThat(page.locator("input[type=number]")).hasValue(Pattern.compile("[0-9]"));
參數
-
value
String | Pattern Added in: v1.18#Expected value.
-
options
LocatorAssertions.HasValueOptions
(optional)
傳回值
hasValues
Added in: v1.23Ensures 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>
page.locator("id=favorite-colors").selectOption(new String[]{"R", "G"});
assertThat(page.locator("id=favorite-colors")).hasValues(new Pattern[] { Pattern.compile("R"), Pattern.compile("G") });
參數
-
Expected options currently selected.
-
options
LocatorAssertions.HasValuesOptions
(optional)
傳回值
isAttached
Added in: v1.33Ensures that Locator points to an element that is connected to a Document or a ShadowRoot.
使用方式
assertThat(page.getByText("Hidden text")).isAttached();
參數
options
LocatorAssertions.IsAttachedOptions
(optional)
傳回值
isChecked
Added in: v1.20Ensures the Locator points to a checked input.
使用方式
assertThat(page.getByLabel("Subscribe to newsletter")).isChecked();
參數
options
LocatorAssertions.IsCheckedOptions
(optional)-
setChecked
boolean (optional) Added in: v1.18#Provides state to assert for. Asserts for input to be checked by default. This option can't be used when setIndeterminate is set to true.
-
setIndeterminate
boolean (optional) Added in: v1.50#Asserts that the element is in the indeterminate (mixed) state. Only supported for checkboxes and radio buttons. This option can't be true when setChecked is provided.
-
setTimeout
double (optional) Added in: v1.18#Time to retry the assertion for in milliseconds. Defaults to
5000
.
-
傳回值
isDisabled
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.
使用方式
assertThat(page.locator("button.submit")).isDisabled();
參數
options
LocatorAssertions.IsDisabledOptions
(optional)
傳回值
isEditable
Added in: v1.20Ensures the Locator points to an editable element.
使用方式
assertThat(page.getByRole(AriaRole.TEXTBOX)).isEditable();
參數
options
LocatorAssertions.IsEditableOptions
(optional)
傳回值
isEmpty
Added in: v1.20Ensures the Locator points to an empty editable element or to a DOM node that has no text.
使用方式
assertThat(page.locator("div.warning")).isEmpty();
參數
options
LocatorAssertions.IsEmptyOptions
(optional)
傳回值
isEnabled
Added in: v1.20Ensures the Locator points to an enabled element.
使用方式
assertThat(page.locator("button.submit")).isEnabled();
參數
options
LocatorAssertions.IsEnabledOptions
(optional)
傳回值
isFocused
Added in: v1.20Ensures the Locator points to a focused DOM node.
使用方式
assertThat(page.getByRole(AriaRole.TEXTBOX)).isFocused();
參數
options
LocatorAssertions.IsFocusedOptions
(optional)
傳回值
isHidden
Added in: v1.20Ensures that Locator either does not resolve to any DOM node, or resolves to a non-visible one.
使用方式
assertThat(page.locator(".my-element")).isHidden();
參數
options
LocatorAssertions.IsHiddenOptions
(optional)
傳回值
isInViewport
Added in: v1.31Ensures the Locator points to an element that intersects viewport, according to the intersection observer API.
使用方式
Locator locator = page.getByRole(AriaRole.BUTTON);
// Make sure at least some part of element intersects viewport.
assertThat(locator).isInViewport();
// Make sure element is fully outside of viewport.
assertThat(locator).not().isInViewport();
// Make sure that at least half of the element intersects viewport.
assertThat(locator).isInViewport(new LocatorAssertions.IsInViewportOptions().setRatio(0.5));
參數
options
LocatorAssertions.IsInViewportOptions
(optional)
傳回值
isVisible
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().
使用方式
// A specific element is visible.
assertThat(page.getByText("Welcome")).isVisible();
// At least one item in the list is visible.
assertThat(page.getByTestId("todo-item").first()).isVisible();
// At least one of the two elements is visible, possibly both.
assertThat(
page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Sign in"))
.or(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Sign up")))
.first()
).isVisible();
參數
options
LocatorAssertions.IsVisibleOptions
(optional)
傳回值
matchesAriaSnapshot
Added in: v1.49Asserts that the target element matches the given accessibility snapshot.
使用方式
page.navigate("https://demo.playwright.dev/todomvc/");
assertThat(page.locator("body")).matchesAriaSnapshot("""
- heading "todos"
- textbox "What needs to be done?"
""");
參數
傳回值
屬性 (Properties)
not()
Added in: v1.20Makes the assertion check for the opposite condition. For example, this code tests that the Locator doesn't contain text "error"
:
assertThat(locator).not().containsText("error");
使用方式
assertThat(locator).not()
傳回值