Saturday, April 12, 2025

Playwright - locator.waitFor()

 locator.waitFor() in Playwright is used to explicitly wait for an element to appear in the DOM and be ready for interaction (visible, attached, etc.), depending on what you specify.

Playwright - locator.waitFor()


 Syntax

await locator.waitFor(options);

 Options

state (optional): One of:

  1. 'attached' – waits for the element to be present in the DOM.
  2. 'detached' – waits for the element to be removed from the DOM.
  3. 'visible' – waits for the element to be present and visible.
  4. 'hidden' – waits for the element to be either not present or not visible.


Example 1: Wait for element to be visible

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


Example 2: Wait for element to be detached

await page.locator('.loading-spinner').waitFor({ state: 'detached' });


When to use waitFor()?

Usually, Playwright auto-waits for elements to be ready before performing actions (like click() or fill()), so you often don’t need it. But it’s useful when:

  1. You're waiting for elements not directly interacted with (e.g. waiting for a spinner to disappear).
  2. You want fine control over timing or presence before proceeding.


No comments:

Post a Comment