skip to Main Content

I’m using Playwright for testing and need to differentiate between an element being hidden with CSS (via display, visibility, opacity, etc.) and an element not being rendered at all, meaning it’s not part of the DOM.

In the Playwright documentation toBeHidden, it states: "Ensures that Locator either does not resolve to any DOM node, or resolves to a non-visible one."

const locator = page.locator('.my-element');
await expect(locator).toBeHidden();

From this test, I can’t determine if .my-element is not rendered or simply hidden.

Is there a way in Playwright to distinguish between an element not being rendered and an element being hidden via CSS?

2

Answers


  1. Not sure if this is an optimal solution, but you can use:

    await expect(loc).toBeAttached();
    await expect(loc).toBeHidden();
    

    if both of these pass — then it’s hidden with CSS.

    Also one could add a layer of abstraction, like:

    await checkMyElementIsHiddenWithCss();
    
    async function checkMyElementIsHiddenWithCss() {
      const locator = page.locator('.my-element');
      await Promise.all([
        expect(loc).toBeAttached(),
        expect(loc).toBeHidden(),
      ]);
    }
    
    Login or Signup to reply.
  2. Here’s the cleanest assertion for the problem:

    await expect(loc).toBeVisible({visible: false});
    

    By default .toBeVisible() asserts the element is attached and visible. {visible: false} asserts that the element is attached, but not visible. (.toBeVisible() docs.)

    That said, the following solution (provided by @d.k), is better if you need to test the criteria separately:

    await expect(loc).toBeHidden();
    await expect(loc).toBeAttached();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search