Component tests with Testing Library
Test components the way users interact with them.
By Invicly Tech, , in Frontend with React & Next.js. About 10 minutes to read.
In short
Testing Library renders components and lets tests interact with them like a user would: finding elements by role and label, typing and clicking. Tests that avoid internals survive refactors.
Explained simply
A component test renders one React component, for example a login form, and then uses it the way a person would. It finds the email box by its label, types into it, clicks the button and checks what appears on screen.
React Testing Library is the standard tool for this. Its main idea is simple: the more your tests look like the way people use your app, the more you can trust them. So you never check a component's internal state; you check the text, buttons and messages a user would see.
Tests written this way keep passing when you refactor. You can rename a state variable, split a component in two or switch from useState to a reducer, and the test still passes as long as the user sees the same thing.
There is a bonus. Finding elements by their role and label only works if they are accessible. So a test that can find the Sign in button by role is also a quick check that screen reader users can find it too.
Press Play on a diagram to walk through it one step at a time.
- Test to Component: render(<LoginForm />)1render(<LoginForm />)
- Test to Rendered DOM: getByLabelText('Email')2getByLabelText('Email')
- Test to Rendered DOM: user.type and user.click3user.type and user.click
- Rendered DOM to Component: Events trigger handlers4Events trigger handlers
- Component to Rendered DOM: Re-render with error text5Re-render with error text
- Test to Rendered DOM: Expect alert to be visible6Expect alert to be visible
- Returns the element now
- Throws if 0 or 2+ matches
- For things already on screen
- Returns element or null
- Never throws for 0 matches
- For asserting something is absent
- Returns a promise
- Retries until found or timeout
- For content that appears later
In depth
Rendering and the screen object
render(component) mounts the component into a document.body provided by jsdom, a browser simulation that runs in Node. After that, the screen object queries the whole document, so you rarely need the values render returns. Testing Library unmounts everything after each test automatically when your runner exposes a global afterEach (in Vitest, set globals: true or call cleanup yourself).
Components often need providers: a router, a theme, a data-fetching client or a context with the current user. Pass a wrapper option to render, or write your own renderWithProviders helper once and use it everywhere. Install @testing-library/jest-dom and import it in the setup file to get readable matchers: toBeInTheDocument, toBeVisible, toHaveTextContent, toBeDisabled, toHaveValue and toHaveAccessibleName. When a test fails and you cannot see why, screen.debug() prints the current DOM.
- screen.debug() prints the DOM; logRoles(container) lists roles
- render(ui, { wrapper: Providers })
- Keep providers in one test-utils file
Choosing the right query
Each query comes in three flavours. getBy returns the element, and throws if there are none or more than one; use it for things that should be there now. queryBy returns null instead of throwing, so it is the only good way to assert that something is absent: expect(screen.queryByText(/error/i)).not.toBeInTheDocument(). findBy returns a promise and retries until the element appears or a timeout passes (1000 ms by default); use it after anything asynchronous. Each has an All version (getAllBy and so on) for lists.
Testing Library recommends a priority order based on how users find things. Prefer getByRole with a name option, such as getByRole("button", { name: /save/i }). Then getByLabelText for form fields, getByPlaceholderText, getByText, getByDisplayValue, then getByAltText and getByTitle. getByTestId is the last resort, for elements with no accessible role or text.
- Accessible to everyone
- getByRole + name
- getByLabelText
- getByPlaceholderText
- getByText
- getByDisplayValue
- Semantic attributes
- getByAltText
- getByTitle
- Last resort
- getByTestId (data-testid)
Simulating users with user-event
@testing-library/user-event fires the full chain of browser events a real person causes. A click includes pointer down, mouse down, focus, pointer up, mouse up and click. Typing fires keydown, keypress, input and keyup for each character. The older fireEvent.click fires only the single click event, so it can miss bugs, such as a handler attached to onMouseDown.
With user-event version 14, call const user = userEvent.setup() at the start of the test, before render, and await every action: await user.type(input, "hello"), await user.click(button), await user.keyboard("{Enter}"), await user.tab(), await user.selectOptions(select, "fr"), await user.clear(input). user-event also respects the rules of the page: it will not type into a disabled input, and clicking an element covered by pointer-events: none fails, just as it would for a person.
- Dispatches one click event
- Synchronous
- Ignores focus and disabled rules
- Fine for rare low-level cases
- Full pointer and mouse sequence
- Async: await every call
- Moves focus like a browser
- The default choice
Asserting on visible output, including async data
Assert on what the user can perceive: text that appears, a button that becomes disabled, an input's value, an element that disappears. Avoid checking props passed to child components, state values or CSS class names, which change during refactors without changing behaviour.
For data loaded with fetch, control the network. You can spy on globalThis.fetch with vi.spyOn and mockResolvedValue, or use Mock Service Worker (MSW), which intercepts requests at the network level so your component code stays untouched. Then wait for the result with await screen.findByText(...) or waitFor(() => expect(...)). Do not wrap getBy in waitFor just to be safe, and do not put side effects like clicks inside waitFor, because it may run them many times. If React warns that an update was not wrapped in act, it usually means something changed after the test ended; await the final state you expect.
- await screen.findByRole("alert")
- await waitForElementToBeRemoved(() => screen.queryByText(/loading/i))
- within(row).getByRole("button", { name: /delete/i })
Learn it in 4 short steps
About 1h each. Track them with a timer in your plan.
- 1Render components in tests~1h
- 2Query elements by role and label~1h
- 3Simulate typing and clicks with user-event~1h
- 4Assert on visible output, not internals~1h
Key points
- Query by role, label or text first; use test IDs only as a last resort.
- user-event simulates real typing and clicking more faithfully than fireEvent.
- Use findBy queries to wait for content that appears asynchronously.
- Assert on what users see, not on state or component internals.
Key terms
Tap a card to flip it. 0/5 known
Examples
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, it } from 'vitest';
import { LoginForm } from './LoginForm';
it('shows an error for an invalid email', async () => {
const user = userEvent.setup();
render(<LoginForm />);
await user.type(screen.getByLabelText(/email/i), 'nope');
await user.click(screen.getByRole('button', { name: /sign in/i }));
expect(await screen.findByRole('alert')).toHaveTextContent(/valid email/i);
});Find by label and role, act like a user, assert on visible text.
A list that loads from an API
UserList fetches /api/users on mount, shows Loading... and then a list. Step 1: spy on fetch and return a fake response with two users. Step 2: render and check the loading text with getByText, because it is there immediately. Step 3: findAllByRole waits for the list items. Step 4: queryByText proves the loading text is gone.
import { render, screen } from '@testing-library/react';
import { expect, it, vi } from 'vitest';
import { UserList } from './UserList';
it('shows users after loading', async () => {
vi.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true, json: async () => [{ id: 1, name: 'Asha' }, { id: 2, name: 'Ben' }],
} as Response);
render(<UserList />);
expect(screen.getByText(/loading/i)).toBeInTheDocument();
expect(await screen.findAllByRole('listitem')).toHaveLength(2);
expect(screen.queryByText(/loading/i)).not.toBeInTheDocument();
});Clicking the right button inside a list row
Every row in a todo list has its own Delete button, so getByRole("button", { name: /delete/i }) would find several and throw. Step 1: pass a vi.fn as the onDelete prop. Step 2: pick the second row with getAllByRole. Step 3: within(row) limits the search to that row. Step 4: assert the callback got the second todo's id.
import { render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, it, vi } from 'vitest';
import { TodoList } from './TodoList';
it('deletes the chosen todo', async () => {
const user = userEvent.setup();
const onDelete = vi.fn();
render(<TodoList todos={[{ id: 'a', text: 'Milk' }, { id: 'b', text: 'Eggs' }]} onDelete={onDelete} />);
const row = screen.getAllByRole('listitem')[1];
await user.click(within(row).getByRole('button', { name: /delete/i }));
expect(onDelete).toHaveBeenCalledWith('b');
});Quick reference
- getBy: must exist now; queryBy: may be absent; findBy: will appear (async)
- screen.getByRole("button", { name: /save/i }) is the default query
- const user = userEvent.setup(); then await user.click / type / keyboard
- expect(screen.queryByText(/x/)).not.toBeInTheDocument() checks absence
- within(element) scopes queries to part of the page
- import "@testing-library/jest-dom/vitest" in the setup file for matchers
- screen.debug() prints the DOM when a query fails
- Mock the network (vi.spyOn on fetch, or MSW), not your component internals
Common mistakes
- Querying by CSS class, which ties tests to styling.
- Using getBy for content that loads later instead of findBy.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Test that a Counter component shows Count: 0 and Count: 1 after clicking the Increment button.
- Exercise 2medium
A SignupForm's Submit button is disabled until the Email field has text. Test both states.
- Exercise 3hard
A SearchBox calls onSearch(query) when the user presses Enter, but not for an empty query. Test both cases with a mock function.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between React Testing Library and Jest or Vitest?
- Vitest or Jest is the test runner: it finds and runs tests and provides expect. React Testing Library renders components and offers user-centred queries. You use them together.
- When is it OK to use data-testid?
- When an element has no accessible role, label or text that identifies it, such as a decorative chart container. Treat it as a last resort, because it does not check accessibility.
- Why do I get a warning that an update was not wrapped in act?
- Something in the component updated state after your test stopped waiting, often a fetch that resolved late. Await the final UI state with findBy or waitFor so the update happens inside the test.
- Should I use snapshot tests for components?
- Use them sparingly. Large snapshots break on every markup change and get approved without reading. Specific assertions on visible text and roles are clearer and more stable.