Test Automation Blog

Tools, Tips and Thoughts for Playwright, Selenium UI and API automated testing

How to wait for an element to be visible in Playwright without using assert

Most of the time when you want to check an element is visible in Playwright you do so as part of a test assertion. For example if you’re testing that attempting to log in using an invalid password displays an error message, your test might look something like this:

test('cannot login with invalid password', async ({ page }) => {
  await page.goto('https://www.mysite.com/login');

  await page.locator('#username').fill('bob@gmail.com');
  await page.locator('#password').fill('bad-password!');
  await page.locator('#loginButton').click();

  await expect(page.locator('#errorMessage')).toBeVisible();
});

This is absolutely fine because checking whether the element is visible is the test verification required and therefore part of the assertion.

However sometimes you just want to wait for an element to become visible, you don’t want to actually do an assertion. Often this is when you have dynamic elements that appear and disappear from the web page.

So how do we do that?

await page.locator('#myElement').waitFor({ state: 'visible' });

You can also wait for an element to disappear:

await page.locator('#myElement').waitFor({ state: 'hidden' });

How to wait for an element to be visible in Playwright without using assert

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top