So there's ways to assert on if a locator is "visible", or attached, or in the viewport, but none of these are quite what I'm looking for. At the moment, I'm trying to assert that something is no longer visible - as in from the perspective of a user. This differs from any of these existing assertion tools in that the node is STILL technically in the viewport, it's computed styles are visible, the DOM node is very much attached, but the element has been scrolled underneath a "sticky header" and so as far as a user would be concerned, is no longer visible.
Is there a way to assert on this? That the node itself is, from a user perspective, no longer visible? Either because it's out of the viewport OR because it's actually covered by another element? (or it's hidden, or anything else that might make it not visible to a user at that moment)
This thread is trying to answer question "Is there a way to assert that an element is no longer visible from a user's perspective, either because it's out of the viewport or because it's covered by another element?"
Related Ask AI answer for "How can I use Playwright to check if an element is hidden or not in the viewport?".
Playwright provides handy methods to check if an element is visible or not.
toBeHidden()
The toBeHidden()
assertion from the LocatorAssertions
class checks if a locator doesn't resolve to any DOM node or resolves to a non-visible one. Here's how you can use it:
const locator = page.locator('button');
await expect(locator).toBeHidden();
This code checks if a button on your page is hidden. If the button isn't visible, the assertion passes. If it's visible, the assertion fails.
toBeInViewport()
Playwright also offers the toBeInViewport()
assertion. This checks if an element intersects with the viewport according to the intersection observer API. Here's how to use it:
const locator = page.locator('button');
await expect(locator).not.toBeInViewport(); // Asserts that at least some part of element is outside of viewport
await expect(locator).toBeInViewport({ ratio: 0.5 }); // Asserts that at least half of the element intersects with viewport
These assertions consider factors like bounding box, computed styles, and animation frames to accurately determine element visibility.
So, with Playwright, you can easily assert whether an element is visible or not from a user's perspective. This is useful for checking if an element is out of the viewport or covered by another element during automated testing.
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].