typescript - 如何在 Playwright 中編寫 waitForElementText 方法
我希望在 Playwright 中有 waitForElementText()。
例如,我在每一頁都有標題 cssSelector='.header-name'。
而我從首頁導航到使用者
我向該方法傳遞兩個參數:waitForElementText( locator: string, expectedText: string)
我想要等待標題名稱從 Home → Users 變更
我嘗試使用 page.waitForFunction() 方法,但我收到錯誤:
page.waitForFunction: TypeError: Cannot read properties of undefined (reading 'locator')
答案#1
由於 Playwright 的定位器 API 會自動等待元素並且具有基於文本的選取器,waitForText 已經在 API 中以 getByText 的形式提供:
await page.getByText("Users"); // for a substring match
// or an "exact" match (after whitespace normalization):
await page.getByText("Users", {exact: true});
// or as an assertion:
await expect(page.getByText("Users", {exact: true})).toBeVisible();
如果這不足以消除元素的歧義,你可以鏈接定位器:
const playwright = require("playwright"); // ^1.39.0
const html = `<!DOCTYPE html><html><body>
<h1 class="header-name"> Users </h1></body></html>`;
let browser;
(async () => {
browser = await playwright.firefox.launch();
const page = await browser.newPage();
await page.setContent(html);
await page
.locator(".header-name")
.getByText("Users", {exact: true})
.waitFor();
})()
.catch(err => console.error(err))
.finally(() => browser?.close());
答案#2
使用自動重試斷言 toHaveText
它 會等到 定位器指向具有指定文字的元素。您也可以對該值使用正規表達式。
const locator = page.locator('.title');
await expect(locator).toHaveText(/Welcome, Test User/);
await expect(locator).toHaveText(/Welcome, .*/);
