← Back to Frontend, page 3

frontend-0048 · Medium mid

What is the philosophy of Testing Library, and why do tests query by role instead of by class name or component internals?

Testing Library tests the page the way a user uses it: find elements by role, label or text, click, type and read what appears. Tests then survive refactors that keep behaviour, and a query by role also fails when the accessibility of the element is broken.

Full answer

A test that reads class names, component state or the number of calls to an internal function is tied to how the code is written. A refactor that keeps the behaviour breaks it. A bug that breaks the real behaviour can pass it. These are false failures and false confidence.

Testing Library suggests tests resemble real use. Its queries follow the order of preference:

  1. By role and accessible name: getByRole('button', { name: 'Save' }). This is how assistive tools see the page.
  2. By label text for form fields: getByLabelText('Email').
  3. By visible text, placeholder or display value.
  4. By test id (data-testid) only when nothing user-facing works.

Benefits: the query documents what a user sees, it checks that the element has the right role and name, and it does not care if the markup changes from a div to a section.

Other rules that follow from the idea:

  • Interact with events that a user causes: click, type, tab. Prefer the user-event library over raw event dispatch where it is available, because it also fires the intermediate events that the browser fires.
  • Assert on visible results, such as text, roles and states, not on component state.
  • Use findBy queries or waitFor for things that appear later, and avoid fixed sleeps.
  • Use queryBy to assert that something is absent, because getBy throws.
  • Mock the network edge and not the components in between.

Limits: a simulated DOM such as jsdom does not do layout, so tests about size, position or CSS need a real browser.

The script uses the DOM version of Testing Library with jsdom. It builds a toggle button, finds it by role and name, clicks it, and finds it again by the new name and its aria-pressed state. The old name no longer matches.

javascript
import { JSDOM } from 'jsdom';
import { getByRole, queryByRole, fireEvent } from '@testing-library/dom';

const { document } = new JSDOM('<!doctype html><body><div id="root"></div></body>').window;
const root = document.getElementById('root');

function mountToggle(parent) {
  let liked = false;
  const button = document.createElement('button');
  const render = () => {
    button.textContent = liked ? 'Liked' : 'Like';
    button.setAttribute('aria-pressed', String(liked));
  };
  button.addEventListener('click', () => { liked = !liked; render(); });
  render();
  parent.append(button);
}
mountToggle(root);

const button = getByRole(root, 'button', { name: 'Like' });
fireEvent.click(button);
console.log('found again by new name and state:', getByRole(root, 'button', { name: 'Liked', pressed: true }) === button);
console.log('old name gone:', queryByRole(root, 'button', { name: 'Like' }) === null);

Run with Node 24.22.1. The output matched the text in the answer in two runs. Run with Node 24, jsdom and @testing-library/dom. The output was identical in two runs. jsdom has no layout, and no component framework was used.

Key points

  • Test as a user does: find by role, label or text, then interact.
  • Prefer getByRole with a name, then label, then text, and test ids last.
  • Assert on visible output, not on component internals.
  • A role query also checks accessibility.
  • jsdom has no layout, so layout needs a real browser.

Common mistakes

  • Querying by CSS class or by component name.
  • Using test ids for everything.
  • Using getBy to assert that an element is not there.
  • Using fixed delays instead of findBy or waitFor.

Follow-ups

  • When is a test id acceptable?
  • What is the difference between getBy, queryBy and findBy?
  • Which behaviour needs a real browser instead of jsdom?

Tips

  • State the guiding idea in one sentence, then give the query order.
  • Say why role queries also help accessibility.