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_class() | 元素具有指定的 CSS 类 |

| 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(locator).to_match_aria_snapshot() | 元素与提供的 Aria 快照匹配 |

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