跳到正文
本页尚未翻译成中文,以下为英文原文。 查看英文版

Assertions ​

Introduction ​

Playwright includes web-specific assertions that automatically retry until the expected condition is met. Consider the following example:

java
assertThat(page.getByTestId("status")).hasText("Submitted");

Playwright will re-test the element with the test ID of status until it has the "Submitted" text. It will re-fetch the element and check it repeatedly until the condition is met or the timeout is reached.

By default, the timeout for assertions is 5 seconds.

Auto-retrying assertions ​

The following assertions will retry until the assertion passes or the assertion timeout is reached.

AssertionDescription
locatorAssertions.isAttached()Element is attached
locatorAssertions.isChecked()Checkbox is checked
locatorAssertions.isDisabled()Element is disabled
locatorAssertions.isEditable()Element is editable
locatorAssertions.isEmpty()Container is empty
locatorAssertions.isEnabled()Element is enabled
locatorAssertions.isFocused()Element is focused
locatorAssertions.isHidden()Element is not visible
locatorAssertions.isInViewport()Element intersects viewport
locatorAssertions.isVisible()Element is visible
locatorAssertions.containsClass()Element has specified CSS classes
locatorAssertions.containsText()Element contains text
locatorAssertions.hasAccessibleDescription()Element has a matching accessible description
locatorAssertions.hasAccessibleName()Element has a matching accessible name
locatorAssertions.hasAttribute()Element has a DOM attribute
locatorAssertions.hasClass()Element has a class property
locatorAssertions.hasCount()List has exact number of children
locatorAssertions.hasCSS()Element has CSS property
locatorAssertions.hasId()Element has an ID
locatorAssertions.hasJSProperty()Element has a JavaScript property
locatorAssertions.hasRole()Element has a specific ARIA role
locatorAssertions.hasText()Element matches text
locatorAssertions.hasValue()Input has a value
locatorAssertions.hasValues()Select has options selected
locatorAssertions.matchesAriaSnapshot()Element matches provided Aria snapshot
pageAssertions.hasTitle()Page has a title
pageAssertions.hasURL()Page has a URL
apiResponseAssertions.isOK()Response has an OK status

Setting a custom timeout ​

You can specify a custom timeout for assertions either globally or per assertion. The default timeout is 5 seconds.

Global timeout ​

java
import com.microsoft.playwright.assertions.PlaywrightAssertions;

PlaywrightAssertions.setDefaultAssertionTimeout(10_000);

Per assertion timeout ​

java
import com.microsoft.playwright.assertions.LocatorAssertions;

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;

assertThat(page.getByText("Name")).isVisible(
    new LocatorAssertions.IsVisibleOptions().setTimeout(10_000));

基于 Apache 2.0 许可证发布。