Skip to main content
← Back to Blog
2026-02-21 · 7 min readWeb DevelopmentDev ToolsUpdated Oct 29, 2026

Automated Testing in React: Unit Testing with Jest and React Testing Library

A hands-on guide to unit testing React components with Jest and React Testing Library. You set up Jest with Babel and jsdom, mock axios, and test a newsletter signup form with user-event: the first render, the loading state, a successful request and an error. Includes the query priority from the Testing Library docs and when to use findBy instead of waitFor.

Avnish Yadav
AI Automation Engineer & Salesforce Developer
9 views
Automated Testing in React: Unit Testing with Jest and React Testing Library

Clicking through a form by hand after every change is slow, and it's easy to skip the error case. This guide is for React developers who want those checks to run on their own. You'll set up Jest and React Testing Library, then test a newsletter signup form the way a user would use it: type an email, click the button, and check what appears. The tests cover the first render, the loading state, a successful request and a failed one.

This is part 23 of the Frontend & JavaScript Fundamentals series. It follows navigation and data flow patterns, and the form here uses the same useState patterns from earlier parts.

Key takeaways

  • Jest runs the tests and checks results; React Testing Library renders components and finds elements the way users do.
  • Find elements by role and label, not by class or id, and drive them with user-event rather than fireEvent.
  • Mock the network, then use findBy queries to wait for the result of an async request.

Jest and React Testing Library: who does what

Jest is a JavaScript test runner. It finds your test files, runs them, gives you expect() for assertions and lets you mock modules. React Testing Library renders a React component into a simulated DOM and gives you queries to find elements in it. You use them together.

The Testing Library docs state the idea behind the library in one line: "The more your tests resemble the way your software is used, the more confidence they can give you." So you test what the user sees and does, not the component's internal state.

Set up the test environment

React deprecated Create React App in February 2025, and the Jest docs say Jest isn't supported by Vite; they point to Vitest, which has a Jest-compatible API. The setup below works in any project that uses Babel, or in an empty folder for practice.

Changed from the earlier version

The original version of this post said Create React App and Vite ship with Jest. Neither is true today, so this version sets Jest up by hand.

In an empty folder, run npm init -y and install the app's own packages first. Skip this line in a project that already has them.

npm install react react-dom axios

Then install Jest, the jsdom environment, Babel and the Testing Library packages:

npm install --save-dev jest jest-environment-jsdom babel-jest @babel/core @babel/preset-env @babel/preset-react
npm install --save-dev @testing-library/react @testing-library/dom @testing-library/user-event @testing-library/jest-dom

The React Testing Library docs say to install @testing-library/dom alongside it, because it's a peer dependency. Then add three small files to the project root.

// babel.config.js
module.exports = {
  presets: [
    ['@babel/preset-env', { targets: { node: 'current' } }],
    ['@babel/preset-react', { runtime: 'automatic' }],
  ],
};
// jest.config.js
module.exports = {
  testEnvironment: 'jsdom',
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
};
// jest.setup.js
import '@testing-library/jest-dom';

Checked against jest@30.5.2, @testing-library/react@16.3.3, @testing-library/user-event@14.6.8, @testing-library/jest-dom@7.0.1, babel-jest@30.5.2, @babel/core@7.29.7 (also run with @babel/core@8.0.9), react@19.3.1 and axios@1.21.0, 2026-10-29.

Here is why each one is needed:

  • babel.config.js lets Jest read JSX and import syntax. The targets line comes from the Jest docs. runtime: 'automatic' means you don't need import React in every file; it's the default in Babel 8, and setting it keeps Babel 7 working too.
  • testEnvironment: 'jsdom' gives tests a browser-like document. The Jest docs say the default is a plain Node.js environment, and the jsdom environment is a separate package.
  • jest.setup.js loads the jest-dom matchers, such as toBeInTheDocument() and toBeDisabled(), once for every test file. setupFilesAfterEnv runs it before each file.

Add "test": "jest" to the scripts in package.json, and npm test runs everything.

The component under test

The form has four states: idle, loading, success and error. It posts the email with axios. Save it as NewsletterForm.jsx.

import { useState } from 'react';
import axios from 'axios';

export default function NewsletterForm() {
  const [email, setEmail] = useState('');
  const [status, setStatus] = useState('idle'); // idle, loading, success, error

  const handleSubmit = async (e) => {
    e.preventDefault();
    setStatus('loading');
    try {
      await axios.post('/api/subscribe', { email });
      setStatus('success');
      setEmail('');
    } catch {
      setStatus('error');
    }
  };

  return (
    <div>
      <h2>Subscribe to the newsletter</h2>
      {status === 'success' ? (
        <div role="alert">You are subscribed!</div>
      ) : (
        <form onSubmit={handleSubmit}>
          <label htmlFor="email-input">Email address</label>
          <input
            id="email-input"
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            disabled={status === 'loading'}
          />
          <button type="submit" disabled={status === 'loading'}>
            {status === 'loading' ? 'Subscribing…' : 'Subscribe'}
          </button>
          {status === 'error' && <div role="alert">Something went wrong. Try again.</div>}
        </form>
      )}
    </div>
  );
}

Test 1: the form renders

Create NewsletterForm.test.jsx next to the component. The jest.mock('axios') line replaces every axios function with a mock, so no test ever reaches a real server. The Jest docs show this same pattern for axios: mock the module, then tell axios.post what to return in each test.

import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import axios from 'axios';
import NewsletterForm from './NewsletterForm';

jest.mock('axios');

afterEach(() => {
  jest.resetAllMocks();
});

test('renders the form', () => {
  render(<NewsletterForm />);

  expect(screen.getByRole('heading', { name: /subscribe to the newsletter/i })).toBeInTheDocument();
  expect(screen.getByLabelText(/email address/i)).toBeInTheDocument();
  expect(screen.getByRole('button', { name: /subscribe/i })).toBeInTheDocument();
});

Why query by role and label

The Testing Library docs rank queries by how close they are to what users experience. getByRole comes first, "for just about everything", then getByLabelText and getByText. Test ids come last.

// Avoid: tied to markup the user never sees
const { container } = render(<NewsletterForm />);
container.querySelector('.btn-primary');

// Better: finds the element the way a user or screen reader does
screen.getByRole('button', { name: /subscribe/i });

A bonus: if you swap the <button> for a clickable <div>, getByRole('button') fails. The test catches markup that keyboard and screen reader users can't use.

Test 2: the loading state

To check the loading state, make the request never finish. mockReturnValueOnce with a promise that never settles keeps the form in "loading" for as long as the test needs.

test('shows a loading state while the request is in flight', async () => {
  axios.post.mockReturnValueOnce(new Promise(() => {})); // never settles
  const user = userEvent.setup();
  render(<NewsletterForm />);

  await user.type(screen.getByLabelText(/email address/i), 'reader@test.dev');
  await user.click(screen.getByRole('button', { name: /subscribe/i }));

  expect(screen.getByRole('button', { name: /subscribing/i })).toBeDisabled();
  expect(screen.getByLabelText(/email address/i)).toBeDisabled();
});

Why user-event instead of fireEvent

The user-event docs explain the difference: fireEvent dispatches single DOM events, while user-event simulates the full interaction. Typing with user.type fires key events for each character, and user.click checks that the element can be clicked first. The docs recommend calling userEvent.setup() before you render, then awaiting each action.

// Avoid: one synthetic change event, no key presses, no checks
fireEvent.change(input, { target: { value: 'reader@test.dev' } });

// Better: types each character the way a user would
const user = userEvent.setup();
await user.type(input, 'reader@test.dev');

Test 3: a successful request

Now let the mock resolve. After the click, the success message appears only once the promise settles and React updates, so the test has to wait for it.

test('subscribes successfully', async () => {
  axios.post.mockResolvedValueOnce({ data: { success: true } });
  const user = userEvent.setup();
  render(<NewsletterForm />);

  await user.type(screen.getByLabelText(/email address/i), 'reader@test.dev');
  await user.click(screen.getByRole('button', { name: /subscribe/i }));

  expect(await screen.findByRole('alert')).toHaveTextContent(/you are subscribed/i);
  expect(axios.post).toHaveBeenCalledWith('/api/subscribe', { email: 'reader@test.dev' });
});

findByRole returns a promise. The Testing Library docs say findBy queries retry until the element appears, for up to 1000 ms by default. That's the same as waitFor around a getBy query, in one call.

Query If nothing matches Waits? Use it for
getBy… Throws No Elements that should be there now
queryBy… Returns null No Checking that something is absent
findBy… Rejects after the timeout Yes, retries Elements that appear after async work

Test 4: a failed request

Manual checks tend to follow the happy path. Automated tests make the failure case cheap to cover, so add it.

test('shows an error when the request fails', async () => {
  axios.post.mockRejectedValueOnce(new Error('Network Error'));
  const user = userEvent.setup();
  render(<NewsletterForm />);

  await user.type(screen.getByLabelText(/email address/i), 'reader@test.dev');
  await user.click(screen.getByRole('button', { name: /subscribe/i }));

  expect(await screen.findByRole('alert')).toHaveTextContent(/something went wrong/i);
  expect(screen.getByRole('button', { name: /subscribe/i })).toBeEnabled();
});

The last line checks that the user can try again: the button is back and enabled. Run npm test, and all four tests should pass.

Habits that keep tests useful

Test behavior, not implementation. Don't reach into component state or check which hook was called. If you later move this form to a data-fetching library, the tests above still pass, because what the user sees hasn't changed.

Mock at the edge. Mocking axios works for one component. For larger apps, Mock Service Worker (MSW) intercepts requests at the network level, so your components use their real fetch code against a fake server.

Arrange, act, assert. Each test above sets up the mock and renders (arrange), types and clicks (act), then checks the screen (assert). Keeping that order makes a failing test easy to read.

Run tests on every pull request. Tests only protect you if they run. Add npm test to your CI pipeline, such as GitHub Actions, and block merges when it fails.

Next in the series, debugging with Chrome DevTools covers what to do when a test, or the app, fails in ways you didn't expect.

Frequently asked questions

What is the difference between Jest and React Testing Library?

Jest is the test runner: it finds and runs test files, provides expect() and mocks modules. React Testing Library renders components and gives you queries to find elements as a user would. You need both, plus jest-dom for DOM matchers such as toBeInTheDocument().

Can I use Jest with Vite?

The Jest docs say Jest isn't supported by Vite because of incompatibilities with Vite's plugin system. They suggest Vitest, which has a Jest-compatible API. React Testing Library, user-event and jest-dom all work with Vitest; jest-dom has a @testing-library/jest-dom/vitest import for it.

Should I use waitFor or findBy?

For waiting until one element appears, use a findBy query, which retries until it finds the element or times out. Use waitFor when you need to wait for something that isn't a single element, such as a mock being called.

Why does my test say "not wrapped in act(...)"?

As a rule of thumb, that warning means state changed after the test stopped waiting, for example after a request resolved. Await the user-event actions and wait for the final screen with a findBy query. That gives React time to finish its updates inside the test.

Should I aim for 100% code coverage?

Coverage shows which lines ran, not whether the important behavior works. As a rule of thumb, cover the paths users depend on, including errors, before chasing a percentage. The four tests here cover every state the form can be in.

Sources

Verified against the sources below on October 29, 2026. Products and docs change often: check the linked sources if something looks different.

  1. Jest docs: Getting Started
  2. Jest docs: Configuring Jest (testEnvironment, setupFilesAfterEnv)
  3. Jest docs: Mock Functions (mocking modules)
  4. Testing Library: React Testing Library introduction
  5. Testing Library: Guiding Principles
  6. Testing Library: About Queries
  7. Testing Library: user-event introduction
  8. Testing Library: jest-dom
  9. jest-dom README (usage)
  10. Babel docs: @babel/preset-react
  11. React blog: Sunsetting Create React App
  12. Mock Service Worker docs
All 30 parts in this series
  1. Part 01Overcoming the Daunting Start: A Strategic Roadmap for New Frontend Developers
  2. Part 02Beyond the Tags: Mastering HTML Architecture for Product-Based Roles
  3. Part 03From Selectors to BEM: CSS Concepts You Must Know for Professional Projects
  4. Part 04Mastering the Primitives: A Builder's Guide to JavaScript Data Types and Functions
  5. Part 05Demystifying Scope and Closure: Key Concepts for Writing Robust JavaScript
  6. Part 06Beyond Frameworks: Practical DOM Manipulation Techniques for High-Performance UIs
  7. Part 07From Prototypes to ES6 Classes: Understanding JavaScript's Object-Oriented Nature
  8. Part 08Architecting Scalable JavaScript: OOP Principles & Design Patterns
  9. Part 09Mastering the Metal: Essential Web APIs & Browser Internals for Frontend Engineers
  10. Part 10Understanding the JavaScript Runtime: Event Loop, Call Stack, and Task Queue Explained
  11. Part 11Mastering Asynchronous Operations with JavaScript Promises: A Builder's Guide
  12. Part 12Modern Async Patterns: Making Asynchronous Code Readable with Async/Await and Generators
  13. Part 13Inside the V8 Engine: A Deep Dive into JavaScript Execution
  14. Part 14Demystifying CORS, HTTP, and Security: A Builder’s Guide
  15. Part 15REST vs. GraphQL: A Frontend Engineer’s Reality Check
  16. Part 16Secure Frontend Auth: The Definitive Guide to JWTs, Cookies, and Storage Strategies
  17. Part 17Why TypeScript Matters: Adding Type Safety to Your JavaScript Projects
  18. Part 18Getting Started with React: Deconstructing JSX and Component Architecture
  19. Part 19React Architecture: Mastering State and Props in Class vs. Functional Components
  20. Part 20Mastering React Hooks: From useState to Building a Production-Ready Custom Hook
  21. Part 21React State Management: Context API vs. Redux & Building a Theme Switcher
  22. Part 22React Architecture: Advanced Navigation and Data Flow Patterns
  23. Part 23Automated Testing in React: Unit Testing with Jest and React Testing Library
  24. Part 24Mastering Chrome DevTools: Debugging Techniques That Save Hours of Development Time
  25. Part 25Automating Code Quality: The Modern Stack with ESLint, Prettier, and Husky
  26. Part 26Demystifying the Build Pipeline: A Deep Dive into Webpack and Babel Configuration
  27. Part 27Improving Performance with Server-Side Rendering: Concepts and Implementation
  28. Part 28From Development to Production: A Builder's Guide to Frontend Deployment Strategies
  29. Part 29Introduction to Micro Frontends: Building Scalable Architectures
  30. Part 30The Frontend Architecture: From Junior Developer to Tech Lead
Written by

Avnish Yadav

AI Automation Engineer & Salesforce Developer

Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.

About meLinkedIn

Share
Discussion

Comments

Loading comments...

Add a comment

Comments are reviewed before they appear.