You rename one CSS class. You click around the app and everything works. Then you run your tests, and half of them are red.
Nothing is broken for your users. Your tests were just looking at the wrong things.
That's the problem Testing Library solves. Testing Library is a set of small tools that test your UI the way a person uses it: find things by what they see, do what they do, and check what shows up on the screen. React Testing Library is the version for React.
Let's learn it with one tiny component and one button.
Meet the button
Here's the whole component we'll test. A heading, an email box and a Subscribe button. When you submit, a thank-you line appears.
// Subscribe.jsx
import { useState } from 'react';
export function Subscribe() {
const [done, setDone] = useState(false);
return (
<form onSubmit={(e) => { e.preventDefault(); setDone(true); }}>
<h2>Weekly React tips</h2>
<label htmlFor="email">Email</label>
<input id="email" type="email" />
<button className="btn-primary">Subscribe</button>
{done && <p>Thanks for subscribing!</p>}
</form>
);
}
Now, how would you find that button if you were looking at the page? You wouldn't think "the element with class btn-primary". You'd think "the button that says Subscribe".
Hold on to that thought. It's the whole idea.
Two ways to find one button
Here are two tests that both find the same button:
// Test A: like a user
screen.getByRole('button', { name: /subscribe/i });
// Test B: by CSS class
container.querySelector('.btn-primary');
Today, both work. Now watch what happens after a small refactor.
Test A asks the page what a user would ask
Every element on a page has a role. A <button> has the role button. An <h2> is a heading. A text <input> is a textbox. Browsers use these roles to build the accessibility tree, the version of your page that screen readers read out loud.
Every element can also have an accessible name. For a button, that's its text. For an input, it's the text of its <label>.
So getByRole('button', { name: /subscribe/i }) means: "find the thing a screen reader would call button, Subscribe." The /subscribe/i part is a regular expression, so the case of the letters doesn't matter.
Test B asks about the paint job
.btn-primary is a styling detail. Users never see class names. Screen readers ignore them.
So when someone renames the class to .button--main and wraps the button in a new <div>, test B can't find it anymore. It fails. But the app still works perfectly. That's a false alarm, and false alarms teach a team to stop trusting their tests.
Test A doesn't care. There's still a button called "Subscribe" on the page, so it stays green.
Testing Library sums this up in one line: the more your tests resemble the way your software is used, the more confidence they can give you.
💡 This idea is taught hands-on in the React course on DevTrail. You even build a tiny
getByRoleyourself, so you see exactly how roles and names are matched. It all runs in your browser, with nothing to install.
There's a bonus, too. If getByRole can't find your button (say it's a clickable <div> with no name), a screen reader user can't find it either. Your test just found an accessibility bug for free.
The query ladder
Testing Library gives you many ways to find things, called queries. Use them roughly in this order, top first:
-
getByRole: a button, link, heading, checkbox, by its name. Your default. -
getByLabelText: form fields, by their label. Great for inputs. -
getByPlaceholderText: only if there is no label (but you should add one). -
getByText: plain text, like a paragraph or a message. -
getByDisplayValue,getByAltText,getByTitle: special cases. -
getByTestId: last resort, when nothing a user can see will work.
The rule of thumb: if a user can't see it or hear it, it should be your last choice.
Your first complete test
Let's set up a Vite project for testing. Install the tools:
npm install -D vitest jsdom @testing-library/react @testing-library/dom @testing-library/user-event @testing-library/jest-dom
Quick tour of what each one does:
- Vitest runs your tests (Jest works almost the same way).
- jsdom is a pretend browser that lives inside Node.
- @testing-library/react draws your component into that pretend browser.
- @testing-library/user-event clicks and types like a real person.
-
@testing-library/jest-dom adds readable checks like
toBeInTheDocument().
Tell Vitest to use jsdom, and load the extra checks before every test:
// vite.config.js (add the test block)
test: {
environment: 'jsdom',
globals: true,
setupFiles: './vitest.setup.js',
},
// vitest.setup.js
import '@testing-library/jest-dom/vitest';
Now the test itself:
// Subscribe.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Subscribe } from './Subscribe';
test('thanks the user after they subscribe', async () => {
const user = userEvent.setup();
render(<Subscribe />);
await user.type(screen.getByLabelText(/email/i), 'a@b.com');
await user.click(screen.getByRole('button', { name: /subscribe/i }));
expect(await screen.findByText(/thanks/i)).toBeInTheDocument();
});
Run npx vitest and it passes.
Read it out loud and it sounds like a person using the app:
- Show the Subscribe form.
- Type an email into the box labelled "Email".
- Click the button called "Subscribe".
- See a thank-you message.
Notice what the test doesn't know. It doesn't know about useState. It doesn't know the state is called done. It doesn't know any class names. You could rewrite the component with a reducer, a form library or a fetch call, and as long as the user sees the same thing, the test stays green.
A few details worth knowing:
-
userEvent.setup()creates a "user". Its actions are async, so alwaysawaitthem. -
user.typepresses every key, one by one, just like real typing. It fires focus, key and input events, not one fake event. -
screenis the whole rendered page. You don't need to keep the return value ofrender. -
findByTextwaits for the message to appear. Here it shows up right away, but if you later add a real API call, this line keeps working.
getBy, queryBy or findBy?
Every query comes in three flavours. The difference is what happens when the element isn't there.
| Flavour | If nothing matches | Use it when |
|---|---|---|
getBy... |
Throws an error right away | The element should be on screen now |
queryBy... |
Returns null
|
You want to check something is not there |
findBy... |
Returns a promise; keeps retrying, rejects after about 1 second | The element shows up later |
So to check that an error message is gone, use queryBy:
expect(screen.queryByText(/invalid email/i)).not.toBeInTheDocument();
(Each one also has an "All" version, like getAllByRole, for when you expect several matches.)
The mistake almost everyone makes: testing the inside
When people start testing React, they reach for the parts they wrote: the state, the class names, the methods.
// 🚨 Tied to the inside of the component
expect(container.querySelector('.btn-primary')).toBeTruthy();
expect(screen.getByTestId('email-input')).toBeInTheDocument();
These tests break when you refactor and stay green when the feature is actually broken. That's the worst of both worlds.
Two related habits to drop:
-
getByTestIdfor everything. Addingdata-testidto every element feels safe, but users can't see test ids. You lose the free accessibility check, too. Keep it for the rare case where nothing visible works. -
Wrapping things in
act()by hand.renderanduser-eventalready do that for you. If you see the warning "An update to Subscribe inside a test was not wrapped in act(...)", the fix is usually toawaitthe user action, or to wait for the final screen withfindBy. Not to add moreact.
The simple rule: test what the user can see and do. If a user can't notice the change, your test shouldn't either.
What you'd learn next
You've written your first real component test. Real apps need a few more tricks:
- ✅ What Testing Library is, queries, and a first test with user-event (this post)
- 🔒 Mocking API calls in tests, from
vi.spyOn(fetch)to MSW - 🔒 Async UI in depth: loading, empty and error states,
waitFor - 🔒 A custom
renderthat wraps components in routers, themes and providers - 🔒 Testing custom hooks
- 🔒 What to test (and what to skip): a sensible coverage strategy
- 🔒 Accessibility in React, so
getByRolefinds everything - 🔒 Debugging React apps when a test (or the screen) shows the wrong thing
🚀 Go from zero to hero with React
This post covered one lesson from Module 17: Testing & Quality. The full React: Basic to Advanced course on DevTrail takes you from your first component all the way there: 17 modules and 90 hands-on lessons, covering state, Hooks in Depth, How React Renders, Performance, Concurrent React & React 19, Server Components and testing.
Every lesson has code you run and check right in your browser. No setup, no "works on my machine".
Module 1 is free. Start the React course →

Top comments (0)