Skip to main content

断言

断言列表

¥List of assertions

断言描述
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()元素具有类属性
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()响应状态为 OK

自定义 Expect 消息

¥Custom Expect Message

你可以指定自定义期望消息作为 expect 函数的第二个参数,例如:

¥You can specify a custom expect message as a second argument to the expect function, for example:

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

当 Expect 失败时,错误将如下所示:

¥When expect fails, the error would look like this:

    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 Actual value: None
E Call log:
E LocatorAssertions.to_be_visible with timeout 5000ms
E waiting for get_by_text("Name")
E waiting for get_by_text("Name")

tests/test_foobar.py:22: AssertionError

设置自定义超时

¥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

conftest.py
from playwright.sync_api import expect

expect.set_options(timeout=10_000)

每个断言超时

¥Per assertion timeout

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)