Перейти к основному содержимому

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

containsText

Added in: v1.20 locatorAssertions.containsText

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

assertThat(page.locator(".title")).containsText("substring");

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

  1. Locator resolves to a list of elements.
  2. Elements from a subset of this list contain text from the expected array, respectively.
  3. The matching subset of elements has the same order as the expected array.
  4. 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"});

Arguments

  • 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 of element.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.


hasAccessibleDescription

Added in: v1.44 locatorAssertions.hasAccessibleDescription

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

Usage

Locator locator = page.getByTestId("save-button");
assertThat(locator).hasAccessibleDescription("Save results to disk");

Arguments

  • description String | Pattern#

    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.

    • setTimeout double (optional)#

      Time to retry the assertion for in milliseconds. Defaults to 5000.

Returns


hasAccessibleErrorMessage

Added in: v1.50 locatorAssertions.hasAccessibleErrorMessage

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

Usage

Locator locator = page.getByTestId("username-input");
assertThat(locator).hasAccessibleErrorMessage("Username is required.");

Arguments

  • 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.

    • setTimeout double (optional)#

      Time to retry the assertion for in milliseconds. Defaults to 5000.

Returns


hasAccessibleName

Added in: v1.44 locatorAssertions.hasAccessibleName

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

Usage

Locator locator = page.getByTestId("save-button");
assertThat(locator).hasAccessibleName("Save to disk");

Arguments

  • name String | Pattern#

    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.

    • setTimeout double (optional)#

      Time to retry the assertion for in milliseconds. Defaults to 5000.

Returns


hasAttribute

Added in: v1.20 locatorAssertions.hasAttribute

Ensures the Locator points to an element with given attribute.

Usage

assertThat(page.locator("input")).hasAttribute("type", "text");

Arguments

  • name String Added in: v1.18#

    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.

Returns


hasClass

Added in: v1.20 locatorAssertions.hasClass

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 or perform partial matches, use a regular expression:

Usage

<div class='middle selected row' id='component'></div>
assertThat(page.locator("#component")).hasClass(Pattern.compile("(^|\\s)selected(\\s|$)"));
assertThat(page.locator("#component")).hasClass("middle selected row");

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"});

Arguments

  • expected String | Pattern | String[] | Pattern[] Added in: v1.18#

    Expected class or RegExp or a list of those.

  • options LocatorAssertions.HasClassOptions (optional)

    • setTimeout double (optional) Added in: v1.18#

      Time to retry the assertion for in milliseconds. Defaults to 5000.

Returns


hasCount

Added in: v1.20 locatorAssertions.hasCount

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

Usage

assertThat(page.locator("list > .component")).hasCount(3);

Arguments

  • count int Added in: v1.18#

    Expected count.

  • options LocatorAssertions.HasCountOptions (optional)

    • setTimeout double (optional) Added in: v1.18#

      Time to retry the assertion for in milliseconds. Defaults to 5000.

Returns


hasCSS

Added in: v1.20 locatorAssertions.hasCSS

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

Usage

assertThat(page.getByRole(AriaRole.BUTTON)).hasCSS("display", "flex");

Arguments

  • name String Added in: v1.18#

    CSS property name.

  • value String | Pattern Added in: v1.18#

    CSS property value.

  • options LocatorAssertions.HasCSSOptions (optional)

    • setTimeout double (optional) Added in: v1.18#

      Time to retry the assertion for in milliseconds. Defaults to 5000.

Returns


hasId

Added in: v1.20 locatorAssertions.hasId

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

Usage

assertThat(page.getByRole(AriaRole.TEXTBOX)).hasId("lastname");

Arguments

  • id String | Pattern Added in: v1.18#

    Element id.

  • options LocatorAssertions.HasIdOptions (optional)

    • setTimeout double (optional) Added in: v1.18#

      Time to retry the assertion for in milliseconds. Defaults to 5000.

Returns


hasJSProperty

Added in: v1.20 locatorAssertions.hasJSProperty

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

assertThat(page.locator("input")).hasJSProperty("loaded", true);

Arguments

  • name String Added in: v1.18#

    Property name.

  • value Object Added in: v1.18#

    Property value.

  • options LocatorAssertions.HasJSPropertyOptions (optional)

    • setTimeout double (optional) Added in: v1.18#

      Time to retry the assertion for in milliseconds. Defaults to 5000.

Returns


hasRole

Added in: v1.44 locatorAssertions.hasRole

Ensures 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

Locator locator = page.getByTestId("save-button");
assertThat(locator).hasRole(AriaRole.BUTTON);

Arguments

  • 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)

    • setTimeout double (optional)#

      Time to retry the assertion for in milliseconds. Defaults to 5000.

Returns


hasText

Added in: v1.20 locatorAssertions.hasText

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

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:

  1. Locator resolves to a list of elements.
  2. The number of elements equals the number of expected values in the array.
  3. 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"});

Arguments

  • 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 of element.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.


hasValue

Added in: v1.20 locatorAssertions.hasValue

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

Usage

assertThat(page.locator("input[type=number]")).hasValue(Pattern.compile("[0-9]"));

Arguments

  • value String | Pattern Added in: v1.18#

    Expected value.

  • options LocatorAssertions.HasValueOptions (optional)

    • setTimeout double (optional) Added in: v1.18#

      Time to retry the assertion for in milliseconds. Defaults to 5000.

Returns


hasValues

Added in: v1.23 locatorAssertions.hasValues

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>
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") });

Arguments

  • values String[] | Pattern[]#

    Expected options currently selected.

  • options LocatorAssertions.HasValuesOptions (optional)

    • setTimeout double (optional)#

      Time to retry the assertion for in milliseconds. Defaults to 5000.

Returns


isAttached

Added in: v1.33 locatorAssertions.isAttached

Убеждается, что Locator указывает на элемент, который подключен к Document или ShadowRoot.

Usage

assertThat(page.getByText("Hidden text")).isAttached();

Arguments

  • options LocatorAssertions.IsAttachedOptions (optional)
    • setAttached boolean (optional)#

    • setTimeout double (optional)#

      Время для повторной попытки утверждения в миллисекундах. По умолчанию 5000.

Returns


isChecked

Added in: v1.20 locatorAssertions.isChecked

Убеждается, что Locator указывает на отмеченный input.

Usage

assertThat(page.getByLabel("Subscribe to newsletter")).isChecked();

Arguments

  • options LocatorAssertions.IsCheckedOptions (optional)
    • setChecked boolean (optional) Added in: v1.18#

      Предоставляет состояние для утверждения. По умолчанию утверждает, что input отмечен. Этот параметр нельзя использовать, когда setIndeterminate установлен в true.

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

      Утверждает, что элемент находится в неопределенном (смешанном) состоянии. Поддерживается только для чекбоксов и радиокнопок. Этот параметр не может быть true, когда setChecked предоставлен.

    • setTimeout double (optional) Added in: v1.18#

      Время для повторной попытки утверждения в миллисекундах. По умолчанию 5000.

Returns


isDisabled

Added in: v1.20 locatorAssertions.isDisabled

Убеждается, что Locator указывает на отключенный элемент. Элемент отключен, если у него есть атрибут "disabled" или он отключен через 'aria-disabled'. Обратите внимание, что только элементы управления, такие как HTML button, input, select, textarea, option, optgroup могут быть отключены установкой атрибута "disabled". Атрибут "disabled" на других элементах игнорируется браузером.

Usage

assertThat(page.locator("button.submit")).isDisabled();

Arguments

  • options LocatorAssertions.IsDisabledOptions (optional)
    • setTimeout double (optional) Added in: v1.18#

      Время для повторной попытки утверждения в миллисекундах. По умолчанию 5000.

Returns


isEditable

Added in: v1.20 locatorAssertions.isEditable

Убеждается, что Locator указывает на редактируемый элемент.

Usage

assertThat(page.getByRole(AriaRole.TEXTBOX)).isEditable();

Arguments

  • options LocatorAssertions.IsEditableOptions (optional)
    • setEditable boolean (optional) Added in: v1.26#

    • setTimeout double (optional) Added in: v1.18#

      Время для повторной попытки утверждения в миллисекундах. По умолчанию 5000.

Returns


isEmpty

Added in: v1.20 locatorAssertions.isEmpty

Убеждается, что Locator указывает на пустой редактируемый элемент или на DOM-узел, который не содержит текста.

Usage

assertThat(page.locator("div.warning")).isEmpty();

Arguments

  • options LocatorAssertions.IsEmptyOptions (optional)
    • setTimeout double (optional) Added in: v1.18#

      Время для повторной попытки утверждения в миллисекундах. По умолчанию 5000.

Returns


isEnabled

Added in: v1.20 locatorAssertions.isEnabled

Убеждается, что Locator указывает на включенный элемент.

Usage

assertThat(page.locator("button.submit")).isEnabled();

Arguments

  • options LocatorAssertions.IsEnabledOptions (optional)
    • setEnabled boolean (optional) Added in: v1.26#

    • setTimeout double (optional) Added in: v1.18#

      Время для повторной попытки утверждения в миллисекундах. По умолчанию 5000.

Returns


isFocused

Added in: v1.20 locatorAssertions.isFocused

Убеждается, что Locator указывает на сфокусированный DOM-узел.

Usage

assertThat(page.getByRole(AriaRole.TEXTBOX)).isFocused();

Arguments

  • options LocatorAssertions.IsFocusedOptions (optional)
    • setTimeout double (optional) Added in: v1.18#

      Время для повторной попытки утверждения в миллисекундах. По умолчанию 5000.

Returns


isHidden

Added in: v1.20 locatorAssertions.isHidden

Убеждается, что Locator либо не разрешается ни в один DOM-узел, либо разрешается в невидимый узел.

Usage

assertThat(page.locator(".my-element")).isHidden();

Arguments

  • options LocatorAssertions.IsHiddenOptions (optional)
    • setTimeout double (optional) Added in: v1.18#

      Время для повторной попытки утверждения в миллисекундах. По умолчанию 5000.

Returns


isInViewport

Added in: v1.31 locatorAssertions.isInViewport

Убеждается, что Locator указывает на элемент, который пересекает область просмотра, согласно API наблюдателя пересечений.

Usage

Locator locator = page.getByRole(AriaRole.BUTTON);
// Убедитесь, что хотя бы часть элемента пересекает область просмотра.
assertThat(locator).isInViewport();
// Убедитесь, что элемент полностью вне области просмотра.
assertThat(locator).not().isInViewport();
// Убедитесь, что хотя бы половина элемента пересекает область просмотра.
assertThat(locator).isInViewport(new LocatorAssertions.IsInViewportOptions().setRatio(0.5));

Arguments

  • options LocatorAssertions.IsInViewportOptions (optional)
    • setRatio double (optional)#

      Минимальное соотношение элемента для пересечения области просмотра. Если равно 0, то элемент должен пересекать область просмотра при любом положительном соотношении. По умолчанию 0.

    • setTimeout double (optional)#

      Время для повторной попытки утверждения в миллисекундах. По умолчанию 5000.

Returns


isVisible

Added in: v1.20 locatorAssertions.isVisible

Убеждается, что Locator указывает на подключенный и видимый DOM-узел.

Чтобы проверить, что хотя бы один элемент из списка виден, используйте Locator.first().

Usage

// Конкретный элемент виден.
assertThat(page.getByText("Welcome")).isVisible();

// По крайней мере один элемент в списке виден.
assertThat(page.getByTestId("todo-item").first()).isVisible();

// По крайней мере один из двух элементов виден, возможно, оба.
assertThat(
page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Sign in"))
.or(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Sign up")))
.first()
).isVisible();

Arguments

  • options LocatorAssertions.IsVisibleOptions (optional)
    • setTimeout double (optional) Added in: v1.18#

      Время для повторной попытки утверждения в миллисекундах. По умолчанию 5000.

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

Returns


matchesAriaSnapshot

Added in: v1.49 locatorAssertions.matchesAriaSnapshot

Утверждает, что целевой элемент соответствует данному снимку доступности.

Usage

page.navigate("https://demo.playwright.dev/todomvc/");
assertThat(page.locator("body")).matchesAriaSnapshot("""
- heading "todos"
- textbox "What needs to be done?"
""");

Arguments

  • expected String#
  • options LocatorAssertions.MatchesAriaSnapshotOptions (optional)
    • setTimeout double (optional)#

      Время для повторной попытки утверждения в миллисекундах. По умолчанию 5000.

Returns


Properties

not()

Added in: v1.20 locatorAssertions.not()

Делает проверку утверждения на противоположное условие. Например, этот код проверяет, что Locator не содержит текст "error":

assertThat(locator).not().containsText("error");

Usage

assertThat(locator).not()

Returns