跳到主要內容

斷言

斷言列表

斷言描述
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()回應具有 OK 狀態

自訂 Expect 訊息

您可以將自訂 expect 訊息指定為 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 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)