Rayrun

What is the method to make Playwright wait until an element is no longer visible or does not exist in the DOM during web testing?

Answer

Waiting for Elements in Playwright

When testing with Playwright, you often need to wait for elements to disappear or become hidden. Here's how you can do it.

Waiting for an Element to Not Exist

To wait for an element to not exist, use the waitFor method with the state option set to 'hidden'. This makes Playwright wait until the element is no longer visible.

import { chromium } from 'playwright';

async function waitForElementNotExists() {
  const browser = await chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();

  await page.goto('https://ray.run');

  await page.waitFor('.my-element', { state: 'hidden' });
}

waitForElementNotExists();

Waiting for an Element to Be Hidden

If you want to wait for an element to be hidden (but still exist in the DOM), use the state option with 'visible' and 'hidden'. This makes Playwright wait until the element transitions from being visible to hidden.

import { chromium } from 'playwright';

async function waitForElementHidden() {
  const browser = await chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();

  await page.goto('https://ray.run');

  await page.waitFor('.my-element', { state: 'visible' });
  await page.waitFor('.my-element', { state: 'hidden' });
}

waitForElementHidden();

Remember, these examples assume you've navigated to a webpage and have a page object. You may need to adjust the code based on your testing scenario. Happy testing with Playwright!

References

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Discord Threads

Related Questions

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 luc@ray.run.