How to write waitForElementText method in Playwright

180 views Asked by At

I would like to have waitForElementText() in playwright.

E.g I have headers on each page cssSelector = '.header-name'.

and I navigate from Home page to Users

I pass two arguments to the method: waitForElementText( locator: string, expectedText: string)

and I want to wait for the header name to change from Home → Users

I tried to use page.waitForFunction() method but I get error:

page.waitForFunction: TypeError: Cannot read properties of undefined (reading 'locator')
2

There are 2 answers

0
ggorlen On

Since Playwright's locator's API waits for elements automatically and has a text-based selector, waitForText is already in the API as 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();

You can chain locators if this isn't enough to disambiguate the element:

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());
0
Vishal Aggarwal On

Use auto- retrying assertion toHaveText

It waits until the Locator points to an element with the given text. You can use regular expressions for the value as well.

const locator = page.locator('.title');
await expect(locator).toHaveText(/Welcome, Test User/);
await expect(locator).toHaveText(/Welcome, .*/);