When automating web testing with Playwright, handling visibility properly is crucial, especially when elements share the same text. In this post, we'll explore how Playwright's locator methods handle visibility and how to ensure your tests interact with the right elements.

The Scenario: Multiple Buttons with the Same Text

Imagine you have a web page with two buttons: one is hidden, and one is visible. Both buttons contain the text "Submit":

style="display: none">Submit
Submit

If you attempt to interact with the "Submit" button using getByText, you might run into an issue.

How getByText and getByRole Differ

When you use getByText to locate the button, Playwright may find multiple matching elements, including hidden ones:

await page.getByText('Submit').click();

Since getByText does not automatically filter out hidden elements, you might unintentionally target an invisible button.

On the other hand, getByRole behaves differently—it only finds visible elements by default:

await page.getByRole('button', { name: 'Submit' }).click();

This difference in behavior means that getByRole will not run into the same issue as getByText in cases where hidden elements are present.

Explicitly Filtering for Visibility

To make getByText and other locators behave like getByRole, you need to explicitly filter for visibility. Adding .filter({ visible: true }) ensures only visible elements are considered, avoiding unintended interactions:

await page.getByText('Submit').filter({ visible: true }).click();

This approach works not only for getByText but also for other locator methods like locator() that do not automatically filter out hidden elements.

Conclusion

Understanding how different Playwright locators handle visibility can help ensure that your tests interact with the right elements. getByRole inherently filters out hidden elements, whereas getByText and other locators do not, which can lead to unintended interactions. If you're using getByText or other locators, remember to explicitly filter for visibility when needed.

Happy testing with Playwright!

Useful links