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
Not sure if this is an optimal solution, but you can use:
if both of these pass — then it’s hidden with CSS.
Also one could add a layer of abstraction, like:
Here’s the cleanest assertion for the problem:
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: