How to narrow and chain your Playwright locators



AI Summary

This video explains how to effectively use the locator.end function in Playwright end-to-end testing to handle situations where user-first locators are insufficient. The presenter demonstrates with a demo project where adding or removing a party member raccoon on a sample website is tested. The challenge arises because multiple elements have the same accessible name (e.g., multiple ‘remove’ buttons). Using getByRole alone results in locating multiple elements, causing test ambiguity.

The solution shown is to combine locators by first retrieving a dynamic data attribute (data-test-id) to get the unique identifier of the recently added element, then chaining this with getByRole using locator.end() to ensure the correct button with the exact role and name is selected. This chaining preserves the user-first locator philosophy, ensuring tests mimic user behavior rather than relying on brittle selectors like classes or IDs.

The video goes through setting up the test with navigation, waiting for success messages, retrieving IDs, chaining locators, and finally asserting the element’s removal. The presenter encourages viewers to embrace this approach to write reliable, maintainable tests and also mentions the Checkly tool for synthetic monitoring of apps.