CodePark/ questions / Testing Library queries
START PRACTICINGPRACTICE
Frontend question · Testing › Testing Library queries

A teammate's tests use container.querySelector('.btn-primary') and getByTestId everywhere. What would you change, and when is a test id still acceptable?

I'd replace CSS selectors and most test ids with role and label queries. A test id is still fine when nothing the user can see identifies the element.

The problem: CSS selectors and test ids tie the test to markup details the user never sees.

  • Renaming a class or restructuring the markup breaks the test.
  • The test says nothing about accessibility.

What I'd use instead:

  • getByRole with an accessible name, such as getByRole('button', { name: /save/i }).
  • getByLabelText for form fields.

If you can't find an element by role or label, that often reveals an accessibility bug. Examples: a clickable div, or an input with no label. That bug is worth fixing in the component.

A data-testid is fine when there's no meaningful role or text. Examples:

  • A chart canvas.
  • A layout wrapper you need to scope with within.
  • Dynamic content where the text isn't stable.

Treat a test id as the last resort.

  • CSS selectors and test ids tie tests to markup the user never sees.
  • Prefer getByRole with a name, and getByLabelText for form fields.
  • If an element is hard to find by role, it often has an accessibility bug.
  • Test ids are OK when nothing the user can see identifies the element.