How do you find elements that survive a refactor?
Role and label locators outlast CSS selectors. A data-testid is for the rare case where neither exists.
Target what the user sees
A CSS selector like .btn-primary > span breaks the moment someone renames a class. A role locator like getByRole('button', { name: 'Submit' }) targets what the user sees, so it survives the refactor.
Rewrite this brittle Playwright selector [paste your CSS selector] as a role or label locator, and explain why the new one survives a CSS refactor.
Reach for data-testid last
Use data-testid only for elements with no accessible role (the button, link, or heading type that assistive tech reports) or visible label, like an icon button with no text. Try the accessible locator first, and add a data-testid only when there is nothing else to grab.
When is adding a data-testid attribute justified instead of using a role or label locator?
Role and label locators outlast CSS selectors because they target what the user sees. Reach for data-testid only when nothing accessible exists.
Additional Resources
Explore these carefully curated resources to deepen your understanding and practice the concepts covered in this lesson.

