Skip to main content

断言

介绍

🌐 Introduction

Playwright 包含针对网页的断言,这些断言会自动重试,直到满足预期条件。看看下面的例子:

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

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

Playwright 会一直重新测试测试 ID 为 status 的元素,直到它显示 "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.

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

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

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

设置自定义超时

🌐 Setting a custom timeout

你可以为断言指定自定义超时时间,既可以全局设置,也可以针对单个断言设置。默认超时时间为 5 秒。

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

全局超时

🌐 Global timeout

import com.microsoft.playwright.assertions.PlaywrightAssertions;

PlaywrightAssertions.setDefaultAssertionTimeout(10_000);

每个断言超时

🌐 Per assertion timeout

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