Rayrun
← Back to Discord Forum

Assert page element that changes text after 2 seconds

My pw assert looks like await expect(page.locator('#create-order-action')).toContainText('Plaseaza comanda');

The thing is that by default the application page will show a different text on this element for about 1-2 seconds, THEN it will be changed into the "Plaseaza comanda". Meanwhile, the test fails because finds the initial text.

How do I implement a mechanism that wait for the text to be displayed in a given time? Using polling? and example would help as I see all the polling examples on the internet are related to API calls. Thanks!

This thread is trying to answer question "How do I implement a mechanism that wait for the text to be displayed in a given time?"

2 replies

hi, try this one:

expect(await page.getByText('Plaseaza comanda').waitFor({ state: "visible" })).toBeVisible();
await expect(async () => {
  expect(page.locator('#create-order-action')).toContainText('Plaseaza comanda');
}).toPass({
  timeout: 5000,
});

Answer

Waiting for Text to Appear in Playwright

In Playwright, you can wait for specific text to appear on a webpage using its built-in auto-waiting functionality and web first assertions.

Auto-Waiting and Actionability Checks

Playwright performs actionability checks before executing actions. For example, when you use the page.click() method, Playwright ensures that the element is attached to the DOM, visible, stable, receives events, and is enabled.

await page.click('#myButton');

Web First Assertions

To wait for specific text to appear, use web first assertions like toBeVisible(). This assertion waits until the expected condition is met.

await expect(page.getByText('welcome')).toBeVisible();

Avoid using manual assertions that are not awaiting expect. For example, don't use expect(await page.getByText('welcome').isVisible()).toBe(true), which doesn't wait and immediately returns whether or not the locator is there.

Debugging

Playwright also provides debugging capabilities for local debugging. You can debug your tests live in VSCode by installing the VS Code extension and running tests in debug mode. This allows you to set breakpoints and interactively debug your test code while it runs in a browser window.

In summary, to wait for a specific text to appear in Playwright, utilize auto-waiting, actionability checks, and web first assertions. Avoid manual assertions without awaiting expect and take advantage of debugging features in VSCode for local debugging.

For more tips on writing efficient Playwright tests, check out this blog post.

Related Discord Threads

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].