Testing

test/query-by-role

Tests find elements the way users do - getByRole with a name first, then label and text; test ids only as a last resort.

minormanualfe-testing

Why

A test that clicks getByRole('button', { name: 'Save' }) fails when the button loses its name or role, so it guards accessibility for free and survives markup refactors. A test that clicks .btn-primary or [data-testid=save] passes for a div that no keyboard or screen reader user can use.

Fix

Query in this order: getByRole (with name), getByLabel, getByPlaceholder, getByText, getByDisplayValue, getByAltText, getByTitle, then getByTestId. Do not reach into the DOM with container.querySelector. Drive interactions with @testing-library/user-event (userEvent.setup() in each test) rather than fireEvent.

Examples

// bad
await user.click(container.querySelector('.btn-primary'))
// good
await user.click(screen.getByRole('button', { name: 'Save' }))

Sources

Facts

Id
test/query-by-role
Severity
minor
Check
manual a person reviews it; the report lists it as a checklist
Applies to
jsx
Only in projects with
testing-library playwright cypress
Taught by the skill
fe-testing Front-end testing
Since version
0.1.0

Rule file on GitHub

Read it in the terminal

npx github:dawidolko/frontend-skills explain test/query-by-role