TST-18Recommended
Find elements the way people do
Find elements by their role, label or visible text. Never by CSS classes or page structure that change with the design.
How to do it
Use queries such as getByRole, getByLabel and getByText in Playwright or Testing Library. When nothing visible fits, add a data-testid on purpose. These queries also prove that buttons and fields have accessible names.
Examples
JavaScript example
// Bad: breaks when the design changes
await page.locator('div.card > .btn-primary:nth-child(2)').click();
// Good: survives a redesign and checks the accessible name
await page.getByRole('button', { name: 'Add to cart' }).click();
Python example
# Playwright for Python
page.get_by_role("button", name="Add to cart").click()
Java example
// Playwright for Java
page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Add to cart")).click();
How to check
Search the browser tests for CSS and XPath selectors, such as locator('., locator('#, locator('// or xpath=. There are none, or each has a comment explaining why.
Sources
Related rules
- APP-54 Test every state of every data view in Web app interface
- AXS-21 Put the visible words in the name in Accessibility
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/testing/end-to-end-and-browser-tests/stable-selectors">Agent Wranglers testing playbook</a>. In code you write, add a comment next to it with the same link.