Sub topic 2
Querying by Role, Label, and Text Before Test IDs
This chapter assumes you know React function components, props, state, hooks, basic HTML semantics, and a test runner such as Jest or Vitest. It also assumes you can use promises and async/await.
Choose User-Facing Queries
React Testing Library encourages tests that describe what users can see and do. Prefer queries in this order:
getByRolefor buttons, headings, links, and other semantic elements.getByLabelTextfor form controls with visible labels.getByTextfor visible content.getByTestIdonly when no meaningful user-facing query exists.
The accessible name is the name assistive technology uses for an element. For example, a button containing Save has the accessible name Save.
expect(screen.getByRole('button', { name: 'Save' })).toBeInTheDocument();
expect(screen.getByLabelText('Email')).toBeInTheDocument();
expect(screen.getByText('Profile saved')).toBeInTheDocument();getBy throws when no match exists. queryBy returns null, so it is useful when checking that something is absent. findBy waits for an element that appears asynchronously.
Debug Missing Queries
When a query fails, read the error message first. It often lists the roles and accessible names currently in the document. You can inspect the rendered DOM with screen.debug().
screen.debug();If roles are unclear, import logRoles from @testing-library/dom and inspect the available roles. A missing role often means the markup uses the wrong element, lacks a label, or has an inaccessible name.
Use Readable Assertions
@testing-library/jest-dom adds assertions that describe visible behavior:
expect(screen.getByRole('button', { name: 'Submit' })).toBeEnabled();
expect(screen.getByText('Saved')).toBeInTheDocument();
expect(screen.getByLabelText('Email')).toHaveValue('[email protected]');These assertions explain intent better than checking class names or component state.
Simulate Users and Test Forms
Use user-event instead of calling event handlers directly. It models typing, clicking, focus, and other browser interactions.
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { LoginForm } from './LoginForm';
test('submits the entered email', async () => {
const user = userEvent.setup();
const handleSubmit = jest.fn();
render(<LoginForm onSubmit={handleSubmit} />);
await user.type(screen.getByLabelText('Email'), '[email protected]');
await user.click(screen.getByRole('button', { name: 'Sign in' }));
expect(handleSubmit).toHaveBeenCalledWith({
email: '[email protected]',
});
});This test covers the form from input to callback. It does not depend on React state names or CSS classes.
Exercise
Which query should you try first for a button labeled “Delete account”?
Show answer
Use screen.getByRole('button', { name: 'Delete account' }).