跳到主要内容

断言

断言列表

断言描述
expect(locator).to_be_attached()元素已附加
expect(locator).to_be_checked()复选框已勾选
expect(locator).to_be_disabled()元素不可用
expect(locator).to_be_editable()元素可编辑
expect(locator).to_be_empty()容器为空
expect(locator).to_be_enabled()元素可用
expect(locator).to_be_focused()元素已聚焦
expect(locator).to_be_hidden()元素不可见
expect(locator).to_be_in_viewport()元素与视口相交
expect(locator).to_be_visible()元素可见
expect(locator).to_contain_text()元素包含文本
expect(locator).to_have_accessible_description()元素有匹配的可访问描述
expect(locator).to_have_accessible_name()元素有匹配的可访问名称
expect(locator).to_have_attribute()元素有 DOM 属性
expect(locator).to_have_class()元素有 class 属性
expect(locator).to_have_count()列表有确切的子元素数量
expect(locator).to_have_css()元素有 CSS 属性
expect(locator).to_have_id()元素有 ID
expect(locator).to_have_js_property()元素有 JavaScript 属性
expect(locator).to_have_role()元素有特定的ARIA 角色
expect(locator).to_have_text()元素匹配文本
expect(locator).to_have_value()输入框有值
expect(locator).to_have_values()选择框选项已选中
expect(page).to_have_title()页面有标题
expect(page).to_have_url()页面有 URL
expect(response).to_be_ok()响应状态正常

自定义期望信息

你可以在 expect 函数中将自定义期望信息作为第二个参数指定,例如:

expect(page.get_by_text("Name"), "should be logged in").to_be_visible()

当 expect 失败时,错误信息会如下所示:

    def test_foobar(page: Page) -> None:
> expect(page.get_by_text("Name"), "should be logged in").to_be_visible()
E AssertionError: should be logged in
E 实际值: None
E 调用日志:
E LocatorAssertions.to_be_visible with timeout 5000ms
E 等待 get_by_text("Name")
E 等待 get_by_text("Name")

tests/test_foobar.py:22: AssertionError

设置自定义超时时间

你可以为断言全局或单个断言设置自定义超时时间。默认超时时间为 5 秒。

全局超时时间

conftest.py
from playwright.sync_api import expect

expect.set_options(timeout=10_000)

单个断言超时时间

test_foobar.py
from playwright.sync_api import expect

def test_foobar(page: Page) -> None:
expect(page.get_by_text("Name")).to_be_visible(timeout=10_000)