Skip to main content

斷言

斷言列表

斷言描述
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 函式的第二個參數,例如:

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

當預期失敗時,錯誤會看起來像這樣:

    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

設定自訂逾時

您可以為斷言指定自訂逾時,可以是全域設定或針對每個斷言。預設逾時為 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)