-
Notifications
You must be signed in to change notification settings - Fork 0
playwright 檢查
daniel edited this page Jul 11, 2025
·
5 revisions
- 等待 10 秒
await page.waitForTimeout(10000); // 等待 10 秒(單位是毫秒)
- 文字抓取DOM
await page.getByText('登入', { exact: false }).click();
這行是 Playwright 測試中的一句操作指令,用來找到頁面上包含「登入」文字的元素並點擊它。
# 語法拆解說明
部分 說明
await 等待這個非同步操作完成(這個點擊 .click() 是 Promise)
page 代表目前的瀏覽器分頁(Playwright 測試中操作的對象)
getByText('登入', { exact: false }) 以可見文字來找出 DOM 元素,並允許部分比對
.click() 模擬使用者對找到的元素執行點擊操作
說明 exact: false
{ exact: false }
代表搜尋文字不需要完全匹配,只要包含「登入」就可以命中。
- 設定語系
// 設定 localStorage 中的 local 鍵
await page.evaluate(() => {
localStorage.setItem('local', 'zh-TW');
});
// 重新整理頁面
await page.reload();
- 檢查網頁文字
// 確認畫面上含有「+ 新增」文字的區塊
await expect(page.getByText('+ 新增')).toBeVisible();
等待並檢查頁面上有出現「HiTeach心智圖」這段文字的元素,而且它真的可見。
這是 Playwright 的 Locator API。
'text=HiTeach心智圖' 是一個選擇器,代表要找出畫面上「文字內容是 HiTeach心智圖」的 DOM 元素。
這種寫法相當於 document.querySelector('element that includes this text'),但更聰明、更穩定,支援模糊比對與多語言內容。
- expect(...).toBeVisible()
這是 Playwright 的 Assertion(斷言)語法。
toBeVisible() 的意思是「斷言這個元素有出現在畫面上(不只是存在於 DOM 裡)」。
包含元素沒有被 display:none、沒有被 visibility:hidden、沒有被遮住等等。
- await
因為這些操作是非同步的(要等畫面加載、元素渲染),所以用 await 等待操作完成。
如果你想加點防呆(例如加個錯誤訊息),也可以寫成這樣:
await expect(page.locator('text=HiTeach心智圖'), '應該顯示心智圖標題').toBeVisible();
讓日後 debug 更輕鬆。