When testing with Playwright, you often need to wait for elements to disappear or become hidden. Here's how you can do it.
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();
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!
If you still have questions, please ask a question and I will try to answer it.
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].