Skip to main content

LocatorAssertions

The LocatorAssertions class provides assertion methods that can be used to make assertions about the Locator state in the tests.

using Microsoft.Playwright;
using Microsoft.Playwright.MSTest;

namespace PlaywrightTests;

[TestClass]
public class ExampleTests : PageTest
{
[TestMethod]
public async Task StatusBecomesSubmitted()
{
// ...
await Page.GetByRole(AriaRole.Button, new() { Name = "Sign In" }).ClickAsync();
await Expect(Page.Locator(".status")).ToHaveTextAsync("Submitted");
}
}

方法 (Methods)

ToBeAttachedAsync

Added in: v1.33 locatorAssertions.ToBeAttachedAsync

Ensures that Locator points to an element that is connected to a Document or a ShadowRoot.

使用方式

await Expect(Page.GetByText("Hidden text")).ToBeAttachedAsync();

參數

  • options LocatorAssertionsToBeAttachedOptions? (optional)
    • Attached bool? (optional)#

    • Timeout [float]? (optional)#

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

傳回值


ToBeCheckedAsync

Added in: v1.20 locatorAssertions.ToBeCheckedAsync

Ensures the Locator points to a checked input.

使用方式

var locator = Page.GetByLabel("Subscribe to newsletter");
await Expect(locator).ToBeCheckedAsync();

參數

  • options LocatorAssertionsToBeCheckedOptions? (optional)
    • Checked bool? (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 Indeterminate is set to true.

    • Indeterminate bool? (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 Checked is provided.

    • Timeout [float]? (optional) Added in: v1.18#

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

傳回值


ToBeDisabledAsync

Added in: v1.20 locatorAssertions.ToBeDisabledAsync

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.

使用方式

var locator = Page.Locator("button.submit");
await Expect(locator).ToBeDisabledAsync();

參數

  • options LocatorAssertionsToBeDisabledOptions? (optional)
    • Timeout [float]? (optional) Added in: v1.18#

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

傳回值


ToBeEditableAsync

Added in: v1.20 locatorAssertions.ToBeEditableAsync

Ensures the Locator points to an editable element.

使用方式

var locator = Page.GetByRole(AriaRole.Textbox);
await Expect(locator).ToBeEditableAsync();

參數

  • options LocatorAssertionsToBeEditableOptions? (optional)
    • Editable bool? (optional) Added in: v1.26#

    • Timeout [float]? (optional) Added in: v1.18#

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

傳回值


ToBeEmptyAsync

Added in: v1.20 locatorAssertions.ToBeEmptyAsync

Ensures the Locator points to an empty editable element or to a DOM node that has no text.

使用方式

var locator = Page.Locator("div.warning");
await Expect(locator).ToBeEmptyAsync();

參數

  • options LocatorAssertionsToBeEmptyOptions? (optional)
    • Timeout [float]? (optional) Added in: v1.18#

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

傳回值


ToBeEnabledAsync

Added in: v1.20 locatorAssertions.ToBeEnabledAsync

Ensures the Locator points to an enabled element.

使用方式

var locator = Page.Locator("button.submit");
await Expect(locator).ToBeEnabledAsync();

參數

  • options LocatorAssertionsToBeEnabledOptions? (optional)
    • Enabled bool? (optional) Added in: v1.26#

    • Timeout [float]? (optional) Added in: v1.18#

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

傳回值


ToBeFocusedAsync

Added in: v1.20 locatorAssertions.ToBeFocusedAsync

Ensures the Locator points to a focused DOM node.

使用方式

var locator = Page.GetByRole(AriaRole.Textbox);
await Expect(locator).ToBeFocusedAsync();

參數

  • options LocatorAssertionsToBeFocusedOptions? (optional)
    • Timeout [float]? (optional) Added in: v1.18#

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

傳回值


ToBeHiddenAsync

Added in: v1.20 locatorAssertions.ToBeHiddenAsync

Ensures that Locator either does not resolve to any DOM node, or resolves to a non-visible one.

使用方式

var locator = Page.Locator(".my-element");
await Expect(locator).ToBeHiddenAsync();

參數

  • options LocatorAssertionsToBeHiddenOptions? (optional)
    • Timeout [float]? (optional) Added in: v1.18#

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

傳回值


ToBeInViewportAsync

Added in: v1.31 locatorAssertions.ToBeInViewportAsync

Ensures the Locator points to an element that intersects viewport, according to the intersection observer API.

使用方式

var locator = Page.GetByRole(AriaRole.Button);
// Make sure at least some part of element intersects viewport.
await Expect(locator).ToBeInViewportAsync();
// Make sure element is fully outside of viewport.
await Expect(locator).Not.ToBeInViewportAsync();
// Make sure that at least half of the element intersects viewport.
await Expect(locator).ToBeInViewportAsync(new() { Ratio = 0.5 });

參數

  • options LocatorAssertionsToBeInViewportOptions? (optional)
    • Ratio [float]? (optional)#

      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.

    • Timeout [float]? (optional)#

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

傳回值


ToBeVisibleAsync

Added in: v1.20 locatorAssertions.ToBeVisibleAsync

Ensures 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.
await Expect(Page.GetByText("Welcome")).ToBeVisibleAsync();

// At least one item in the list is visible.
await Expect(Page.GetByTestId("todo-item").First).ToBeVisibleAsync();

// At least one of the two elements is visible, possibly both.
await Expect(
Page.GetByRole(AriaRole.Button, new() { Name = "Sign in" })
.Or(Page.GetByRole(AriaRole.Button, new() { Name = "Sign up" }))
.First
).ToBeVisibleAsync();

參數

  • options LocatorAssertionsToBeVisibleOptions? (optional)
    • Timeout [float]? (optional) Added in: v1.18#

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

    • Visible bool? (optional) Added in: v1.26#

傳回值


ToContainClassAsync

Added in: v1.52 locatorAssertions.ToContainClassAsync

Ensures 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>
var locator = Page.Locator("#component");
await Expect(locator).ToContainClassAsync("middle selected row");
await Expect(locator).ToContainClassAsync("selected");
await Expect(locator).ToContainClassAsync("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>
var locator = Page.Locator(".list > .component");
await Expect(locator).ToContainClassAsync(new string[]{"inactive", "active", "inactive"});

參數

  • expected string | IEnumerable<string>#

    A string containing expected class names, separated by spaces, or a list of such strings to assert multiple elements.

  • options LocatorAssertionsToContainClassOptions? (optional)

    • Timeout [float]? (optional)#

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

傳回值


ToContainTextAsync

Added in: v1.20 locatorAssertions.ToContainTextAsync

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.

使用方式

var locator = Page.Locator(".title");
await Expect(locator).ToContainTextAsync("substring");
await Expect(locator).ToContainTextAsync(new Regex("\\d messages"));

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
await Expect(Page.Locator("ul > li")).ToContainTextAsync(new string[] {"Text 1", "Text 3", "Text 4"});

// ✖ Wrong order
await Expect(Page.Locator("ul > li")).ToContainTextAsync(new string[] {"Text 3", "Text 2"});

// ✖ No item contains this text
await Expect(Page.Locator("ul > li")).ToContainTextAsync(new string[] {"Some 33"});

// ✖ Locator points to the outer list element, not to the list items
await Expect(Page.Locator("ul")).ToContainTextAsync(new string[] {"Text 3"});

參數

  • expected string | Regex | IEnumerable<string> | IEnumerable<Regex> Added in: v1.18#

    Expected substring or RegExp or a list of those.

  • options LocatorAssertionsToContainTextOptions? (optional)

    • IgnoreCase bool? (optional) Added in: v1.23#

      Whether to perform case-insensitive match. IgnoreCase option takes precedence over the corresponding regular expression flag if specified.

    • Timeout [float]? (optional) Added in: v1.18#

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

    • UseInnerText bool? (optional) Added in: v1.18#

      Whether to use element.innerText instead of element.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.


ToHaveAccessibleDescriptionAsync

Added in: v1.44 locatorAssertions.ToHaveAccessibleDescriptionAsync

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

使用方式

var locator = Page.GetByTestId("save-button");
await Expect(locator).ToHaveAccessibleDescriptionAsync("Save results to disk");

參數

  • description string | Regex#

    Expected accessible description.

  • options LocatorAssertionsToHaveAccessibleDescriptionOptions? (optional)

    • IgnoreCase bool? (optional)#

      Whether to perform case-insensitive match. IgnoreCase option takes precedence over the corresponding regular expression flag if specified.

    • Timeout [float]? (optional)#

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

傳回值


ToHaveAccessibleErrorMessageAsync

Added in: v1.50 locatorAssertions.ToHaveAccessibleErrorMessageAsync

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

使用方式

var locator = Page.GetByTestId("username-input");
await Expect(locator).ToHaveAccessibleErrorMessageAsync("Username is required.");

參數

  • errorMessage string | Regex#

    Expected accessible error message.

  • options LocatorAssertionsToHaveAccessibleErrorMessageOptions? (optional)

    • IgnoreCase bool? (optional)#

      Whether to perform case-insensitive match. IgnoreCase option takes precedence over the corresponding regular expression flag if specified.

    • Timeout [float]? (optional)#

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

傳回值


ToHaveAccessibleNameAsync

Added in: v1.44 locatorAssertions.ToHaveAccessibleNameAsync

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

使用方式

var locator = Page.GetByTestId("save-button");
await Expect(locator).ToHaveAccessibleNameAsync("Save to disk");

參數

  • name string | Regex#

    Expected accessible name.

  • options LocatorAssertionsToHaveAccessibleNameOptions? (optional)

    • IgnoreCase bool? (optional)#

      Whether to perform case-insensitive match. IgnoreCase option takes precedence over the corresponding regular expression flag if specified.

    • Timeout [float]? (optional)#

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

傳回值


ToHaveAttributeAsync

Added in: v1.20 locatorAssertions.ToHaveAttributeAsync

Ensures the Locator points to an element with given attribute.

使用方式

var locator = Page.Locator("input");
await Expect(locator).ToHaveAttributeAsync("type", "text");

參數

  • name string Added in: v1.18#

    Attribute name.

  • value string | Regex Added in: v1.18#

    Expected attribute value.

  • options LocatorAssertionsToHaveAttributeOptions? (optional)

    • IgnoreCase bool? (optional) Added in: v1.40#

      Whether to perform case-insensitive match. IgnoreCase option takes precedence over the corresponding regular expression flag if specified.

    • Timeout [float]? (optional) Added in: v1.18#

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

傳回值


ToHaveClassAsync

Added in: v1.20 locatorAssertions.ToHaveClassAsync

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 use Expect(Locator).ToContainClassAsync().

使用方式

<div class='middle selected row' id='component'></div>
var locator = Page.Locator("#component");
await Expect(locator).ToHaveClassAsync("middle selected row");
await Expect(locator).ToHaveClassAsync(new Regex("(^|\\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:

var locator = Page.Locator(".list > .component");
await Expect(locator).ToHaveClassAsync(new string[]{"component", "component selected", "component"});

參數

  • expected string | Regex | IEnumerable<string> | IEnumerable<Regex> Added in: v1.18#

    Expected class or RegExp or a list of those.

  • options LocatorAssertionsToHaveClassOptions? (optional)

    • Timeout [float]? (optional) Added in: v1.18#

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

傳回值


ToHaveCountAsync

Added in: v1.20 locatorAssertions.ToHaveCountAsync

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

使用方式

var locator = Page.Locator("list > .component");
await Expect(locator).ToHaveCountAsync(3);

參數

  • count int Added in: v1.18#

    Expected count.

  • options LocatorAssertionsToHaveCountOptions? (optional)

    • Timeout [float]? (optional) Added in: v1.18#

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

傳回值


ToHaveCSSAsync

Added in: v1.20 locatorAssertions.ToHaveCSSAsync

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

使用方式

var locator = Page.GetByRole(AriaRole.Button);
await Expect(locator).ToHaveCSSAsync("display", "flex");

參數

  • name string Added in: v1.18#

    CSS property name.

  • value string | Regex Added in: v1.18#

    CSS property value.

  • options LocatorAssertionsToHaveCSSOptions? (optional)

    • Timeout [float]? (optional) Added in: v1.18#

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

傳回值


ToHaveIdAsync

Added in: v1.20 locatorAssertions.ToHaveIdAsync

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

使用方式

var locator = Page.GetByRole(AriaRole.Textbox);
await Expect(locator).ToHaveIdAsync("lastname");

參數

  • id string | Regex Added in: v1.18#

    Element id.

  • options LocatorAssertionsToHaveIdOptions? (optional)

    • Timeout [float]? (optional) Added in: v1.18#

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

傳回值


ToHaveJSPropertyAsync

Added in: v1.20 locatorAssertions.ToHaveJSPropertyAsync

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.

使用方式

var locator = Page.Locator(".component");
await Expect(locator).ToHaveJSPropertyAsync("loaded", true);

參數

  • name string Added in: v1.18#

    Property name.

  • value [object] Added in: v1.18#

    Property value.

  • options LocatorAssertionsToHaveJSPropertyOptions? (optional)

    • Timeout [float]? (optional) Added in: v1.18#

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

傳回值


ToHaveRoleAsync

Added in: v1.44 locatorAssertions.ToHaveRoleAsync

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.

使用方式

var locator = Page.GetByTestId("save-button");
await Expect(locator).ToHaveRoleAsync(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 LocatorAssertionsToHaveRoleOptions? (optional)

    • Timeout [float]? (optional)#

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

傳回值


ToHaveTextAsync

Added in: v1.20 locatorAssertions.ToHaveTextAsync

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.

使用方式

var locator = Page.Locator(".title");
await Expect(locator).ToHaveTextAsync(new Regex("Welcome, Test User"));
await Expect(locator).ToHaveTextAsync(new Regex("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
await Expect(Page.Locator("ul > li")).ToHaveTextAsync(new string[] {"Text 1", "Text 2", "Text 3"});

// ✖ Wrong order
await Expect(Page.Locator("ul > li")).ToHaveTextAsync(new string[] {"Text 3", "Text 2", "Text 1"});

// ✖ Last item does not match
await Expect(Page.Locator("ul > li")).ToHaveTextAsync(new string[] {"Text 1", "Text 2", "Text"});

// ✖ Locator points to the outer list element, not to the list items
await Expect(Page.Locator("ul")).ToHaveTextAsync(new string[] {"Text 1", "Text 2", "Text 3"});

參數

  • expected string | Regex | IEnumerable<string> | IEnumerable<Regex> Added in: v1.18#

    Expected string or RegExp or a list of those.

  • options LocatorAssertionsToHaveTextOptions? (optional)

    • IgnoreCase bool? (optional) Added in: v1.23#

      Whether to perform case-insensitive match. IgnoreCase option takes precedence over the corresponding regular expression flag if specified.

    • Timeout [float]? (optional) Added in: v1.18#

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

    • UseInnerText bool? (optional) Added in: v1.18#

      Whether to use element.innerText instead of element.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.


ToHaveValueAsync

Added in: v1.20 locatorAssertions.ToHaveValueAsync

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

使用方式

var locator = Page.Locator("input[type=number]");
await Expect(locator).ToHaveValueAsync(new Regex("[0-9]"));

參數

  • value string | Regex Added in: v1.18#

    Expected value.

  • options LocatorAssertionsToHaveValueOptions? (optional)

    • Timeout [float]? (optional) Added in: v1.18#

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

傳回值


ToHaveValuesAsync

Added in: v1.23 locatorAssertions.ToHaveValuesAsync

Ensures 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>
var locator = Page.Locator("id=favorite-colors");
await locator.SelectOptionAsync(new string[] { "R", "G" });
await Expect(locator).ToHaveValuesAsync(new Regex[] { new Regex("R"), new Regex("G") });

參數

  • values IEnumerable<string> | IEnumerable<Regex>#

    Expected options currently selected.

  • options LocatorAssertionsToHaveValuesOptions? (optional)

    • Timeout [float]? (optional)#

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

傳回值


ToMatchAriaSnapshotAsync

Added in: v1.49 locatorAssertions.ToMatchAriaSnapshotAsync

Asserts that the target element matches the given accessibility snapshot.

使用方式

await page.GotoAsync("https://demo.playwright.dev/todomvc/");
await Expect(page.Locator("body")).ToMatchAriaSnapshotAsync(@"
- heading ""todos""
- textbox ""What needs to be done?""
");

參數

  • expected string#
  • options LocatorAssertionsToMatchAriaSnapshotOptions? (optional)
    • Timeout [float]? (optional)#

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

傳回值


屬性 (Properties)

Not

Added in: v1.20 locatorAssertions.Not

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.ToContainTextAsync("error");

使用方式

Expect(Locator).Not

型別 (Type)