DEV Community

Cover image for Test Like a User: React Testing Library in One Button
Ravindra Singh
Ravindra Singh

Posted on Originally published at ravindrarajpoot9454.hashnode.dev AI-assisted

Test Like a User: React Testing Library in One Button

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

Today, both work. Now watch what happens after a small refactor.

Test A finds the button by role and survives a refactor, test B breaks

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 getByRole yourself, 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:

  1. getByRole: a button, link, heading, checkbox, by its name. Your default.
  2. getByLabelText: form fields, by their label. Great for inputs.
  3. getByPlaceholderText: only if there is no label (but you should add one).
  4. getByText: plain text, like a paragraph or a message.
  5. getByDisplayValue, getByAltText, getByTitle: special cases.
  6. 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
Enter fullscreen mode Exit fullscreen mode

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',
},
Enter fullscreen mode Exit fullscreen mode
// vitest.setup.js
import '@testing-library/jest-dom/vitest';
Enter fullscreen mode Exit fullscreen mode

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();
});
Enter fullscreen mode Exit fullscreen mode

Run npx vitest and it passes.

Read it out loud and it sounds like a person using the app:

  1. Show the Subscribe form.
  2. Type an email into the box labelled "Email".
  3. Click the button called "Subscribe".
  4. 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 always await them.
  • user.type presses every key, one by one, just like real typing. It fires focus, key and input events, not one fake event.
  • screen is the whole rendered page. You don't need to keep the return value of render.
  • findByText waits 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();
Enter fullscreen mode Exit fullscreen mode

(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();
Enter fullscreen mode Exit fullscreen mode

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:

  • getByTestId for everything. Adding data-testid to 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. render and user-event already 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 to await the user action, or to wait for the final screen with findBy. Not to add more act.

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 render that 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 getByRole finds 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)