Jest 26 ๐ React Testing โ React Testing Library integration and component tests
Testing a React component is not the same activity as testing a function. A function takes arguments and returns a value; a component is mounted into a DOM, rendered by React’s reconciler, driven by events that the browser dispatches asynchronously, and updated by state changes that happen on React’s schedule rather than yours. The test has to participate in all four of those, and the tool that makes the participation tolerable is React Testing Library โ a thin layer over react-dom/test-utils whose entire design is a refusal to know anything about your components.
That refusal is the point. React Testing Library renders your component into a container attached to document, hands you queries that find things the way a user would find them, and gives you back a render result whose queries are bound to that container. It does not expose the component instance, does not let you call methods on it, does not let you read or set its state. Everything you assert on has to be visible in the DOM, which is exactly the surface a user interacts with and exactly the surface a refactor is not allowed to break without consequence.
Jest’s contribution is the runner and the environment: a jsdom implementation of the DOM that gives React something to render into inside Node, a module system that can be mocked, fake timers that can advance time without waiting, and snapshot serialization for the cases where a structural comparison is genuinely the right assertion. The two halves are joined by a setup file, a matcher extension, and a small number of rules about asynchronous state updates that every React test eventually has to learn.
This chapter covers the integration in four parts. The first is the render-and-query model โ render, screen, the query priority ladder, and why getByRole is the default rather than getByTestId. The second is events โ userEvent against fireEvent, the setup() call, the pointer-events rules that decide whether a click lands, and the interaction between user events and fake timers. The third is asynchronous state โ findBy, waitFor, the act() boundary, and the console warnings that tell you when you have stepped outside it. The fourth is the supporting configuration โ jest-dom matchers, jsdom setup, module mapping, and the places where jsdom cannot do what a browser does.
Key point: React Testing Library can only see what the DOM shows, so every assertion has to be written against something a user could perceive โ getByRole, getByLabelText, getByText โ and every state update React makes has to happen inside act(), which render, userEvent, and waitFor already wrap. The test does not know about props or state; it drives events and reads the rendered output, and that is the whole contract.
Why React Testing Library integration exists
The implementation-coupled test problem. Enzyme, the library that dominated React testing before this one, exposed wrapper.state(), wrapper.instance(), wrapper.setProps(), and wrapper.find('Button'). Those APIs made it easy to assert on things that are not visible to a user โ that a component’s state contains isOpen: true, that a Button component received a particular prop โ and every one of those assertions broke on a refactor that changed nothing about the rendered page. React Testing Library exists as a deliberate replacement: there is no wrapper.instance(), by design, and the migration guides for projects coming from Enzyme are mostly instructions on how to ask the same question in DOM terms.
The “resembles usage” problem. The library’s stated principle is that the more a test resembles the way the software is used, the more confidence it can give. That translates into a concrete ranking of queries: a role with an accessible name first, because that is what a screen reader announces; a label next, because that is what a user reads; a test id last, because it is a string that only the test knows. The ranking is not aesthetic โ a getByRole('button', { name: 'Save' }) query fails when the accessible name is removed, which is a genuine regression for a user with a screen reader, whereas a getByTestId query passes through the same change silently.
The asynchronous rendering problem. React 18 batches state updates and schedules renders, so a setState inside an event handler does not produce an updated DOM synchronously by the time your next line runs. act() is React’s signal that a block of code will cause updates and that the resulting work should be flushed before the block ends. Without it, an assertion runs against the previous render and fails, and the console prints “An update to X inside a test was not wrapped in act(…)” โ the single most common warning in a React test suite, and the one that most often indicates the assertion is racing rather than that React is misbehaving.
The environment problem. Jest does not have a DOM. jest-environment-jsdom supplies one โ a JavaScript implementation of the DOM API sufficient for React, for document.querySelector, and for getComputedStyle on declared styles. It is not a browser: there is no layout, so getBoundingClientRect() returns zeros; there is no painting, so nothing can be visually off-screen; and there is no real event dispatch, so userEvent synthesizes the pointer and keyboard event sequence itself. Knowing which parts of the DOM are simulated is what separates a test that fails for a real reason from one that fails because jsdom cannot measure a box.
The event-fidelity problem. fireEvent.click(button) dispatches one synthetic event and nothing else. A real click fires pointerdown, mousedown, focus, pointerup, mouseup, click, and moves focus in between. Code that opens a menu on pointerdown and closes it on blur behaves differently under the one-event version, and the difference is invisible until a test in production starts failing. userEvent exists to dispatch the full sequence, which is why it is the recommended API and fireEvent is the escape hatch.
The trade-off. React Testing Library’s opacity is a cost as well as a benefit. It cannot tell you why a component re-rendered, cannot assert on a memo boundary, and cannot test a hook in isolation without renderHook. Those are legitimate needs, and the answer is to reach for a different tool for them โ renderHook for hooks, a profiler test for render counts, a unit test for a pure helper โ rather than to reach back through the DOM for the internals. The library is deliberately narrow, and the narrowness is what keeps the suite honest.
a. The render-and-query model
render() mounts a React element into a container that is appended to document.body, and returns a result object carrying queries bound to that container. In current React Testing Library the queries are also available on the screen singleton, and screen is what the documentation recommends โ a test that uses screen reads the same way regardless of how many renders happened.
// src/SaveButton.test.tsx
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom'; // matchers: toBeInTheDocument, etc.
import { SaveButton } from './SaveButton';
test('renders the label', () => {
// mount into a container attached to document.body
render(<SaveButton label="Save" />);
// screen queries the whole document; no container threading needed
expect(screen.getByRole('button', { name: 'Save' })).toBeInTheDocument();
});
The query families differ in three ways, and the difference decides which one a test should use. The prefix decides the throwing behaviour: getBy* throws when nothing matches, queryBy* returns null, and findBy* returns a promise that rejects on timeout. The first is for an element that must exist, the second is for asserting absence, and the third is for an element that appears later.
// getBy: the element must be there right now, or the test fails loudly
screen.getByRole('heading', { name: 'Checkout' });
// queryBy: for asserting absence โ getBy would throw instead of failing the expect
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
// findBy: waits for the element to appear, up to 1000 ms by default
expect(await screen.findByRole('alert')).toHaveTextContent('Saved');
The query type decides what the query matches against, and the ranking matters because it decides what a test is coupled to. getByRole resolves through the accessibility tree โ the implicit role from the element name, filtered by the accessible name computed from the content and any aria-label. getByLabelText reads the <label> association, which is what a sighted user reads and what a screen reader announces for a form field. getByText matches text content in a non-interactive element. getByTestId matches a data-testid attribute and is the last resort because nothing but a test depends on it.
// role + accessible name: the element as assistive technology sees it
screen.getByRole('button', { name: 'Save' });
// label: the way a user reads a form field
screen.getByLabelText('Email address');
// text: for a non-interactive node, like a status message
screen.getByText('Order confirmed');
// test id: stable, but it proves nothing about accessibility
screen.getByTestId('cart-count');
Options narrow a query, and they are preferred to reaching for a more specific selector. name filters by accessible name, level restricts a heading, checked and selected filter by state, and exact: false makes a text match case-insensitive.
screen.getByRole('heading', { level: 1 }); // an <h1> only
screen.getByRole('checkbox', { checked: true }); // a ticked box
screen.getByText(/order confirmed/i); // a regex match
screen.getByRole('link', { name: /docs/i, exact: false }); // substring name
The render result carries the lifecycle pieces the queries do not. rerender() re-renders the same element with new props โ the way to test a prop change without unmounting โ and unmount() tears the component down so a test can assert on cleanup. asFragment() returns a DocumentFragment for a snapshot, and debug() prints the current DOM to the console when a query is not matching and you need to see what is actually there.
const { rerender, unmount, asFragment, debug } = render(<Counter count={0} />);
rerender(<Counter count={5} />); // same instance, new props
expect(screen.getByText('5')).toBeInTheDocument();
expect(asFragment()).toMatchSnapshot(); // structural snapshot
unmount(); // run effect cleanups
The debug() call is worth knowing about because it answers the question every failing query raises. screen.debug() prints the entire document, and screen.debug(element) prints a subtree. When a getByRole fails, the printed DOM almost always shows why โ a missing label association, a <div> where a <button> was expected, or content that has not rendered yet.
For a suite written by someone else or a component with no obvious accessible surface, logRoles() prints every role computed within a container. It is the fastest way to discover that what looked like a button is a <div role="button"> with no accessible name, which is itself a finding worth reporting.
// prints every role in the subtree, with its accessible name
import { logRoles } from '@testing-library/dom';
const { container } = render(<Toolbar />);
logRoles(container);
b. Events โ userEvent over fireEvent
fireEvent dispatches exactly one event. userEvent dispatches the sequence a real user produces, and it is the API to reach for unless there is a specific reason not to. The version matters: userEvent v14 is fully asynchronous, so every interaction returns a promise that has to be awaited.
import userEvent from '@testing-library/user-event';
import { render, screen } from '@testing-library/react';
import { LoginForm } from './LoginForm';
test('submits credentials', async () => {
const user = userEvent.setup(); // set up once, before render
render(<LoginForm />);
await user.type(screen.getByLabelText('Email'), 'a@b.c'); // full key sequence
await user.type(screen.getByLabelText('Password'), 'secret');
await user.click(screen.getByRole('button', { name: 'Sign in' }));
expect(await screen.findByRole('alert')).toHaveTextContent('Welcome');
});
userEvent.setup() must be called before render(), and the reason is concrete rather than stylistic: setup() replaces navigator.clipboard and installs the pointer and keyboard state the interactions depend on, and any code that runs during the render and captures those references โ a useEffect reading the clipboard API, say โ will capture the originals if setup() came second.
// correct order: setup installs the stubs, then the component captures them
const user = userEvent.setup();
render(<CopyButton />);
// wrong order: the component captured the real clipboard during render
render(<CopyButton />);
const user = userEvent.setup();
The click is the interaction that most often fails for a reason that has nothing to do with the test. userEvent refuses to click an element whose computed style is pointer-events: none or that is disabled, and the failure message names the reason. Both behaviours are deliberate โ a real user cannot click through them either โ and the fix is to change the component rather than to force the click.
// a disabled button is not clickable, by the component or by the user
await user.click(screen.getByRole('button', { name: 'Pay' }));
// Error: unable to click element as it has or inherits pointer-events: none
Each of the interaction methods has a natural analogue in the browser’s event sequence, and knowing which event a handler is listening for decides whether userEvent will trigger it. A menu opened on pointerdown is not opened by fireEvent.click, and a dropdown closed on blur is not closed by fireEvent.focus alone.
await user.click(el); // pointerdown, mousedown, focus, pointerup, mouseup, click
await user.dblClick(el); // two full click sequences
await user.type(el, 'text'); // per-character keydown, keypress, input, keyup
await user.clear(el); // focus + select-all + delete
await user.selectOptions(el, 'DE'); // click, open, click the option
await user.tab(); // focus the next element, like a real Tab
await user.keyboard('{Enter}'); // a key without targeting an element
await user.hover(el); // pointerover, pointerenter, mouseover, mouseenter
type() processes special keys in braces, and the ones that matter in practice are the ones a form reads โ {Enter} to submit, {Escape} to close, {Backspace} to correct. The {Shift>} and {/Shift} pair holds a modifier for a sequence, which is how a shift-click range selection is tested.
await user.type(search, 'widget{Enter}'); // typing then submitting
await user.keyboard('{Escape}'); // close a dialog
await user.type(input, '{Shift>}hello{/Shift}'); // select with shift
await user.type(input, '{Backspace}'); // delete one character
Fake timers are the interaction that needs an explicit bridge. userEvent schedules its delays with setTimeout, so a jest.useFakeTimers() call freezes the interactions themselves along with the component’s timers. The advanceTimers option hands userEvent a function that advances the fake clock, which restores the interactions and also makes a debounced input testable without waiting.
beforeEach(() => {
jest.useFakeTimers(); // freeze every timer
});
test('debounces the search input', async () => {
// hand userEvent a way to advance the fake clock, or it hangs
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });
render(<SearchBox />);
await user.type(screen.getByRole('searchbox'), 'abc');
jest.advanceTimersByTime(300); // clear the debounce window
expect(await screen.findByText('3 results')).toBeInTheDocument();
});
fireEvent remains the right tool for the events userEvent does not model โ a scroll, a change on a file input, a submit on a form directly โ and for a codebase that needs a single event and cannot afford the full pointer sequence in a hot test.
import { fireEvent } from '@testing-library/react';
fireEvent.scroll(container, { target: { scrollTop: 500 } }); // no userEvent twin
fireEvent.submit(screen.getByRole('form')); // bypass the click
fireEvent.change(fileInput, { target: { files: [file] } }); // direct file set
c. Asynchronous state โ findBy, waitFor, and the act boundary
A state update inside a click handler does not complete by the time await user.click() resolves in every case, and an update caused by a resolved promise is guaranteed not to. React signals this with the warning “An update to X inside a test was not wrapped in act(…)” and the assertion that follows it usually fails against the previous render.
The three tools for the situation are ranked. findBy* is the first choice because it is a getBy* wrapped in waitFor, so it retries until the element appears and reads naturally. waitFor is the second, for asserting on something that is not a query. await act(async () => {}) is the third, a manual flush, and needing it usually means the test is asserting on the wrong thing.
// first choice: a query that waits for the element to render
expect(await screen.findByRole('alert')).toHaveTextContent('Saved');
// second choice: wait for a condition, then assert on the DOM
await waitFor(() => {
expect(screen.getByTestId('status')).toHaveTextContent('done');
});
// third choice: flush a pending update that no query can observe
await act(async () => { await Promise.resolve(); });
The timeout is the thing to know when a findBy fails intermittently. Both findBy* and waitFor default to 1000 ms with a 50 ms polling interval, and the timeout is configurable globally through configure or per call through the options argument.
import { configure, waitFor } from '@testing-library/react';
// global: for a suite whose API is consistently slow under CI load
configure({ asyncUtilTimeout: 3000 });
// per call: for one test that waits on a slow endpoint
await waitFor(() => expect(screen.getByText('Done')).toBeInTheDocument(), {
timeout: 5000,
interval: 100,
});
The act warning has a second source that is worth separating from the first. Outside Jest’s test environment, React will not warn; inside it, React needs to know that an environment capable of act is present, and the flag that says so is globalThis.IS_REACT_ACT_ENVIRONMENT. React Testing Library sets it during render and restores it afterwards, so the only time it needs setting manually is a test that renders without the library.
// only needed when rendering outside React Testing Library
beforeAll(() => { globalThis.IS_REACT_ACT_ENVIRONMENT = true; });
afterAll(() => { globalThis.IS_REACT_ACT_ENVIRONMENT = false; });
The practical distinction between an assertion that needs waitFor and one that does not is whether the DOM changes after the interaction resolves. A synchronous click handler produces its render before await user.click() returns, and a getBy on the new DOM succeeds immediately. A handler that awaits a fetch or a setTimeout produces its render afterwards, and only a findBy or a waitFor will see it.
// synchronous handler: the DOM is already updated, getBy is correct
await user.click(screen.getByRole('button', { name: 'Toggle' }));
expect(screen.getByText('Open')).toBeInTheDocument();
// asynchronous handler: findBy waits for the render that follows the fetch
await user.click(screen.getByRole('button', { name: 'Load' }));
expect(await screen.findByText('Loaded')).toBeInTheDocument();
d. Matchers, config, and the limits of jsdom
@testing-library/jest-dom extends Jest’s expect with matchers that read in DOM terms, and importing it once in a setup file is enough. The matchers are not cosmetic: toBeVisible computes effective visibility from the ancestors’ display, visibility, opacity, and the hidden attribute, which is a genuinely different question from not.toBeNull().
expect(screen.getByRole('button')).toBeInTheDocument(); // attached to the document
expect(screen.getByRole('alert')).toBeVisible(); // not hidden by an ancestor
expect(screen.getByRole('button')).toBeDisabled(); // disabled or aria-disabled
expect(screen.getByLabelText('Email')).toHaveValue('a@b.c');
expect(screen.getByRole('checkbox')).toBeChecked();
expect(screen.getByRole('link')).toHaveAttribute('href', '/docs');
expect(screen.getByRole('heading')).toHaveTextContent(/welcome/i);
expect(screen.getByRole('textbox')).toHaveFocus();
The Jest configuration is three blocks that need to be right: the environment, the setup file, and the transform. The environment is a separate package since Jest 28 โ jest-environment-jsdom is no longer bundled โ and leaving it out produces a document is not defined failure that looks like a React problem.
// jest.config.js
module.exports = {
testEnvironment: 'jsdom', // jsdom, not node
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'], // matchers, after the env
transform: { '^.+\\.tsx?$': 'ts-jest' }, // or babel-jest
moduleNameMapper: { '\\.(css|scss)$': 'identity-obj-proxy' },
};
// jest.setup.ts โ runs after the environment is installed
import '@testing-library/jest-dom'; // registers the matchers
The setupFilesAfterEnv key is the one that matters and the one most often confused with setupFiles. The former runs after the test framework is installed, which is why it is the right place for jest-dom; the latter runs before, which is the right place for a polyfill. Putting the matcher import in setupFiles produces “expect is not defined” for the same reason.
The jsdom limitations are worth stating because they explain a whole category of confusing failure. There is no layout engine, so getBoundingClientRect() returns a rectangle of zeros, offsetWidth is zero, and an assertion that an element is on screen cannot be made. There is no real focus management across the document, so tab order is whatever userEvent.tab() simulates. There is no rendering, so a stylesheet loaded through import './styles.css' contributes nothing โ which is why the module mapper stubs CSS imports rather than parsing them.
// jsdom has no layout: this is always zeros, not a mounting order problem
const { width } = screen.getByRole('img').getBoundingClientRect();
expect(width).toBe(0); // true in jsdom, never in a browser
// computed styles are only what the CSS in the document declares
element.style.display = 'none';
expect(element).not.toBeVisible(); // works, style is declared
renderHook covers the piece React Testing Library otherwise leaves out โ a custom hook with no component to render it. It returns the hook’s result plus the rerender and unmount controls, and it wraps everything in act so a state update inside the hook is flushed before the assertion reads it.
import { renderHook, act } from '@testing-library/react';
test('increments', () => {
const { result } = renderHook(() => useCounter(0));
act(() => { result.current.increment(); }); // state update inside act
expect(result.current.count).toBe(1);
});
Complete Example Session
// ============================================
// PART 1: THE COMPONENT UNDER TEST
// ============================================
// src/CheckoutForm.tsx
// export function CheckoutForm({ onSubmit }: { onSubmit: (email: string) => void }) {
// const [email, setEmail] = useState('');
// const [error, setError] = useState('');
// ...
// }
// ============================================
// PART 2: THE SETUP FILE
// ============================================
// jest.setup.ts
import '@testing-library/jest-dom'; // toBeInTheDocument, toBeVisible, โฆ
// ============================================
// PART 3: THE JEST CONFIGURATION
// ============================================
// jest.config.js
module.exports = {
testEnvironment: 'jsdom', // the DOM React renders into
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
transform: { '^.+\\.tsx?$': 'ts-jest' },
moduleNameMapper: { '\\.(css|scss)$': 'identity-obj-proxy' },
};
// ============================================
// PART 4: THE RENDER AND THE ROLE QUERY
// ============================================
// src/CheckoutForm.test.tsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { CheckoutForm } from './CheckoutForm';
test('renders the field with its label', () => {
render(<CheckoutForm onSubmit={jest.fn()} />);
// the label association is what a user reads and a screen reader announces
expect(screen.getByLabelText('Email address')).toBeInTheDocument();
});
// ============================================
// PART 5: THE USER INTERACTION
// ============================================
test('submits a valid address', async () => {
const onSubmit = jest.fn();
const user = userEvent.setup(); // before render, always
render(<CheckoutForm onSubmit={onSubmit} />);
// the full key sequence, not a single synthetic event
await user.type(screen.getByLabelText('Email address'), 'a@b.c');
await user.click(screen.getByRole('button', { name: 'Place order' }));
// the mock records the argument the handler produced
expect(onSubmit).toHaveBeenCalledWith('a@b.c');
});
// ============================================
// PART 6: THE VALIDATION PATH
// ============================================
test('rejects an empty address', async () => {
const onSubmit = jest.fn();
const user = userEvent.setup();
render(<CheckoutForm onSubmit={onSubmit} />);
await user.click(screen.getByRole('button', { name: 'Place order' }));
// a *query*, because the element may render a tick later
expect(await screen.findByRole('alert')).toHaveTextContent('required');
expect(onSubmit).not.toHaveBeenCalled(); // no side effect on failure
});
// ============================================
// PART 7: THE ABSENCE ASSERTION
// ============================================
test('shows no error before submission', () => {
render(<CheckoutForm onSubmit={jest.fn()} />);
// queryBy, because getBy would throw instead of failing the expect
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
});
// ============================================
// PART 8: THE ASYNCHRONOUS UPDATE
// ============================================
test('disables the button while submitting', async () => {
const onSubmit = jest.fn(() => new Promise<void>((r) => setTimeout(r, 100)));
const user = userEvent.setup();
render(<CheckoutForm onSubmit={onSubmit} />);
await user.type(screen.getByLabelText('Email address'), 'a@b.c');
await user.click(screen.getByRole('button', { name: 'Place order' }));
// the disabled state appears during the pending promise
expect(screen.getByRole('button', { name: 'Place order' })).toBeDisabled();
// wait for the promise to settle before the test ends
await waitFor(() => expect(screen.getByRole('button')).toBeEnabled());
});
// ============================================
// PART 9: THE RE-RENDER AND THE SNAPSHOT
// ============================================
test('updates when the plan prop changes', () => {
const { rerender, asFragment } = render(<CheckoutForm plan="basic" onSubmit={jest.fn()} />);
expect(screen.getByText('Basic plan')).toBeInTheDocument();
rerender(<CheckoutForm plan="pro" onSubmit={jest.fn()} />);
expect(screen.getByText('Pro plan')).toBeInTheDocument();
expect(asFragment()).toMatchSnapshot(); // structural, for the rare case
});
// ============================================
// PART 10: THE FAKE-TIMER INTERACTION
// ============================================
test('debounces the address check', async () => {
jest.useFakeTimers();
// hand userEvent the clock advancer, or the interactions never resolve
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });
render(<CheckoutForm onSubmit={jest.fn()} />);
await user.type(screen.getByLabelText('Email address'), 'a@b.c');
jest.advanceTimersByTime(500); // clear the debounce window
expect(await screen.findByText('Address available')).toBeInTheDocument();
jest.useRealTimers(); // restore for the next test
});
The ten parts covered the component, the matcher setup, the Jest environment and transform, the label query, the full user interaction, the asynchronous validation path, the absence assertion, the pending-state assertion, the rerender and snapshot pair, and the fake-timer bridge.
Quick Reference
The query families
| Prefix | No match | Multiple matches | Async |
|---|---|---|---|
getBy* | throws | throws | no |
queryBy* | null | throws | no |
findBy* | rejects | rejects | yes |
getAllBy* | throws | array | no |
queryAllBy* | [] | array | no |
findAllBy* | rejects | array | yes |
Query priority
| Query | Matches against |
|---|---|
getByRole | Accessibility tree + name |
getByLabelText | <label> association |
getByPlaceholderText | placeholder attribute |
getByText | Rendered text content |
getByDisplayValue | Current input value |
getByAltText | alt attribute |
getByTitle | title attribute |
getByTestId | data-testid attribute |
Interactions
userEvent | Events dispatched |
|---|---|
click | pointerdown, mousedown, focus, pointerup, mouseup, click |
type | keydown, keypress, beforeinput, input, keyup (per char) |
clear | focus, select-all, delete |
selectOptions | click, pointer sequence, option click |
tab | focus moves to the next tabbable element |
keyboard | keydown/keyup with brace syntax for modifiers |
hover | pointerover, pointerenter, mouseover, mouseenter |
jest-dom matchers
| Matcher | Asks |
|---|---|
toBeInTheDocument | Is it attached? |
toBeVisible | Is it rendered visibly? |
toBeDisabled / toBeEnabled | Is it interactive? |
toHaveTextContent | Does the text match? |
toHaveValue | What is the input value? |
toHaveAttribute | Does the attribute match? |
toHaveAccessibleName | What does a screen reader announce? |
toHaveFocus | Is it focused? |
Timeouts
| Knob | Default |
|---|---|
findBy* timeout | 1000 ms |
waitFor timeout | 1000 ms |
waitFor interval | 50 ms |
configure({ asyncUtilTimeout }) | Global override |
Best Practices
โ Do This:
// Query by role and accessible name first
screen.getByRole('button', { name: 'Save' }); // โ
// Set up userEvent before render
const user = userEvent.setup();
render(<Form />); // โ
// Await every interaction โ v14 is fully async
await user.click(screen.getByRole('button')); // โ
// Use findBy when the DOM changes after the promise resolves
expect(await screen.findByRole('alert')).toBeVisible(); // โ
// Use queryBy only to assert absence
expect(screen.queryByRole('alert')).not.toBeInTheDocument(); // โ
// Bridge fake timers through setup
userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); // โ
// Import jest-dom once, in setupFilesAfterEnv
import '@testing-library/jest-dom'; // โ
โ Don’t Do This:
// Reach for the test id when a role exists
screen.getByTestId('save-button'); // โ
// Use getBy to assert absence โ it throws instead of failing
expect(screen.getByRole('alert')).not.toBeInTheDocument(); // โ
// Dispatch a single synthetic event for a real interaction
fireEvent.click(button); // โ prefer user
// Forget the await โ the interaction never runs
user.click(screen.getByRole('button')); // โ
// Wrap every assertion in waitFor
await waitFor(() => expect(screen.getByText('Hi')).toBeInTheDocument()); // โ
// Assert on layout in jsdom
expect(el.getBoundingClientRect().width).toBeGreaterThan(0); // โ
// Put the matcher import in setupFiles
setupFiles: ['@testing-library/jest-dom']; // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
document is not defined | testEnvironment is node | Set jsdom |
expect is not defined in setup | Matcher import in setupFiles | Move to setupFilesAfterEnv |
act(...) warning | Update outside the act boundary | findBy or waitFor |
| Click does nothing | pointer-events: none or disabled | Fix the component |
| Query finds nothing | Element renders after the assertion | findBy, not getBy |
| Test hangs with fake timers | userEvent frozen | advanceTimers option |
| Clipboard stub not used | setup() after render() | Setup first |
| Width assertion fails | jsdom has no layout | Assert on text, not geometry |
| Snapshot churn | Asserting on the whole tree | Assert on the role, not the fragment |
Real-World Examples
1. Role with a name
screen.getByRole('button', { name: /save/i });
2. Absence
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
3. Full interaction
const user = userEvent.setup();
await user.type(screen.getByLabelText('Email'), 'a@b.c');
4. Wait for a render
expect(await screen.findByText('Loaded')).toBeInTheDocument();
5. Wait for a condition
await waitFor(() => expect(screen.getByTestId('n')).toHaveTextContent('3'));
6. Prop change
rerender(<Counter count={5} />);
expect(screen.getByText('5')).toBeInTheDocument();
7. Fake-timer bridge
userEvent.setup({ advanceTimers: jest.advanceTimersByTime });
8. Hook test
const { result } = renderHook(() => useCounter(0));
act(() => result.current.increment());
9. Debug a failing query
screen.debug(); // prints the current DOM
10. Discover roles
logRoles(render(<Toolbar />).container);
Visual
The query priority ladder
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ QUERY PRIORITY โ ACCESSIBLE FIRST โ
โ โ
โ getByRole accessible name, no DOM knowledge โ
โ getByLabelText form fields โ
โ getByPlaceholderText placeholder only โ
โ getByText non-interactive text โ
โ getByDisplayValue value currently in an input โ
โ getByAltText images โ
โ getByTitle low confidence โ
โ getByTestId last resort, no a11y check โ
โ โ
โ screen.getByRole('button', { name: 'Save' }) โ best โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
fireEvent against userEvent
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ONE EVENT AGAINST THE REAL SEQUENCE โ
โ โ
โ fireEvent.click(el) โ
โ โโ click โ
โ โ
โ await user.click(el) โ
โ โโ pointerdown โ
โ โโ mousedown โ
โ โโ focus โ
โ โโ pointerup โ
โ โโ mouseup โ
โ โโ click โ
โ โ
โ a handler on pointerdown fires only in the second one โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The act boundary
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ THE ACT BOUNDARY โ
โ โ
โ await user.click(button) โ
โ โโ wrapped in act โโโบ state update โโโบ re-render โ
โ โ
โ synchronous handler โ
โ getBy* works immediately after the await โ
โ โ
โ asynchronous handler (fetch, timer) โ
โ update happens after the await returns โ
โ findBy* / waitFor polls until the new render โ
โ โ
โ neither โโโบ "not wrapped in act(...)" warning โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
What jsdom provides
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ WHAT JSDOM PROVIDES โ
โ โ
โ yes document, querySelector, createElement โ
โ yes getComputedStyle on declared inline styles โ
โ yes focus, blur, event dispatch โ
โ yes innerHTML, textContent, attributes โ
โ โ
โ no layout โ getBoundingClientRect returns zeros โ
โ no painting โ nothing is off-screen โ
โ no stylesheets โ CSS imports are stubbed โ
โ no real pointer or keyboard device โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Environment | jest-environment-jsdom (separate package) |
| Matcher setup | setupFilesAfterEnv + @testing-library/jest-dom |
| Render | render(<Component />) โ queries bound to the container |
| Preferred query | screen.getByRole with an accessible name |
| Absence assertion | queryBy* + not.toBeInTheDocument() |
| Deferred assertion | findBy* (1000 ms) or waitFor |
| Interaction | userEvent.setup() then await user.click() |
| Setup order | userEvent.setup() before render() |
| Fake timers | setup({ advanceTimers: jest.advanceTimersByTime }) |
| Hook testing | renderHook + act |
| Unavailable in jsdom | Layout, painting, real stylesheets |
Key takeaways:
- The library can only see the DOM, and that is the design. There is no
wrapper.instance(), nowrapper.state(), no way to assert on a prop that did not reach the output. Every assertion is against something a user could perceive, which means a passing suite is evidence about the rendered page and not about the component’s internals. - Query priority is about coupling, not taste.
getByRole('button', { name: 'Save' })fails when the accessible name is removed, which is a real regression.getByTestId('save')passes through the same change silently. The ladder exists to make the test fail for the reasons a user would care about. - The prefix answers a different question from the type.
getBy*for a thing that must exist,queryBy*to assert absence โ becausegetBythrows rather than failing theexpectโ andfindBy*for a thing that renders later. Choosing the wrong prefix is the most common cause of a test that fails for a reason that has nothing to do with the component. userEventv14 is fully asynchronous and must be set up beforerender.user.click()anduser.type()dispatch the full browser sequence, which is what makes apointerdownhandler testable at all, andsetup()installs the clipboard and pointer state that the render may capture. An un-awaited interaction does not fail loudly; it simply does not run.- The
actwarning usually means the assertion is racing.render,userEvent, andwaitForall wrap inactalready, so a warning points at an update caused by a promise or a timer that the test did not wait for. Replacing thegetBywith afindByfixes the warning and the assertion at the same time. - Fake timers need the
advanceTimersbridge.jest.useFakeTimers()freezesuserEvent‘s own scheduling along with the component’s, and the test hangs rather than failing.setup({ advanceTimers: jest.advanceTimersByTime })restores the interactions and makes a debounce testable without waiting a real second. jsdomis a DOM implementation, not a browser.getBoundingClientRect()returns zeros,offsetWidthis zero, and CSS files are stubbed by the module mapper. A test that asserts on geometry is asserting onjsdom, not on the application, and the correct answer is to assert on the text or the role instead.
Remember: A React component test is a sequence of three moves โ render, interact, assert on the DOM โ and each of the three has one rule that carries most of the weight. Render with render() and query through screen with a role and an accessible name, so the test is coupled to what a user perceives. Interact with userEvent.setup() called first and every interaction awaited, so the full browser event sequence is dispatched. Assert with findBy or waitFor whenever the DOM changes after the interaction resolves, so the assertion waits for the render instead of racing it. The rest of the configuration โ the jsdom environment, setupFilesAfterEnv, the CSS module mapper, the jest-dom matchers โ exists to make those three moves possible and stays out of the way once it is right.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!