跳到正文

断言 ​

简介 ​

Playwright 包含针对 Web 的特定断言,这些断言会自动重试,直到满足预期条件。请考虑以下示例:

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

Playwright 将重新测试具有测试 ID status 的元素,直到它具有 "Submitted" 文本。它将反复重新获取元素并检查,直到满足条件或超时。

默认情况下,断言的超时时间为 5 秒。

自动重试断言 ​

以下断言将重试,直到断言通过或达到断言超时。

断言描述
locatorAssertions.isAttached()元素已附加
locatorAssertions.isChecked()复选框已选中
locatorAssertions.isDisabled()元素已禁用
locatorAssertions.isEditable()元素可编辑
locatorAssertions.isEmpty()容器为空
locatorAssertions.isEnabled()元素已启用
locatorAssertions.isFocused()元素已聚焦
locatorAssertions.isHidden()元素不可见
locatorAssertions.isInViewport()元素与视口相交
locatorAssertions.isVisible()元素可见
locatorAssertions.containsClass()元素具有指定的 CSS 类
locatorAssertions.containsText()元素包含文本
locatorAssertions.hasAccessibleDescription()元素具有匹配的无障碍描述
locatorAssertions.hasAccessibleName()元素具有匹配的无障碍名称
locatorAssertions.hasAttribute()元素具有 DOM 属性
locatorAssertions.hasClass()元素具有 class 属性
locatorAssertions.hasCount()列表具有确切数量的子元素
locatorAssertions.hasCSS()元素具有 CSS 属性
locatorAssertions.hasId()元素具有 ID
locatorAssertions.hasJSProperty()元素具有 JavaScript 属性
locatorAssertions.hasRole()元素具有特定的 ARIA 角色
locatorAssertions.hasText()元素匹配文本
locatorAssertions.hasValue()输入框具有值
locatorAssertions.hasValues()下拉框已选择选项
locatorAssertions.matchesAriaSnapshot()元素匹配提供的 Aria 快照
pageAssertions.hasTitle()页面具有标题
pageAssertions.hasURL()页面具有 URL
apiResponseAssertions.isOK()响应具有 OK 状态

设置自定义超时 ​

您可以全局或按断言指定自定义超时。默认超时为 5 秒。

全局超时 ​

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

PlaywrightAssertions.setDefaultAssertionTimeout(10_000);

按断言超时 ​

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 许可证发布。