ReactJS

Testing React Components With Jest

Testing is an important part of React development. A React application can contain many components, user interactions, API calls, and state changes. As your…

D
DevByteTechnical Author
Published
14 min read5 views
Testing React components with Jest using React Testing Library

Imagine you have built a React application with beautiful components, working forms, and interactive buttons. Everything looks perfect when you test it manually. But after adding a new feature, suddenly your login form stops working, a button no longer responds, or an important component displays the wrong information.

How do you catch these problems before your users do?

This is where automated testing comes in.

Instead of manually checking every component after each code change, you can write tests that automatically verify whether your application behaves as expected.

In the React ecosystem, Jest and React Testing Library are popular tools for testing components. Jest provides a test runner, assertions, and mocking capabilities, while React Testing Library helps you test components through the way users interact with them.

In this beginner-friendly guide, you'll learn how to set up Jest, write your first React component tests, test buttons and forms, handle asynchronous behavior, and understand common testing mistakes.

What Is Jest?

Jest is a JavaScript testing framework originally developed by Facebook, now Meta. It is commonly used to test JavaScript and TypeScript applications, including React projects.

Jest provides several features that make automated testing easier:

  • Test runner: Finds and executes your tests.

  • Assertions: Checks whether actual results match expected results.

  • Mocking: Replaces functions, modules, or dependencies with controlled test implementations.

  • Code coverage: Helps measure which parts of your code are exercised by tests.

  • Snapshot testing: Compares rendered output against a previously saved snapshot.

For example, imagine you have a function that adds two numbers:

function add(a, b) {
  return a + b;
}

module.exports = add;

You can test it using Jest:

const add = require("./add");

test("adds two numbers", () => {
  expect(add(2, 3)).toBe(5);
});

Here, test() defines the test, while expect() and toBe() check whether the result is correct.

When the test runs, Jest reports whether it passes or fails.

However, testing React components involves more than checking the return value of a function. You may also need to verify what appears on the screen and how the component responds to user interactions.

That's where React Testing Library becomes useful.

What Is React Testing Library?

React Testing Library is a library that helps developers test React components by interacting with the rendered interface.

Rather than focusing on a component's internal implementation, it encourages you to test what users can see and do.

For example, instead of checking whether a component contains a particular internal state variable, you can check whether clicking a button updates the displayed count.

This approach makes tests more closely reflect real user behavior.

React Testing Library provides useful functions such as:

  • render() — renders a React component in a test environment.

  • screen — provides queries for finding elements on the rendered page.

  • fireEvent — dispatches DOM events.

  • waitFor() — waits for an expected condition to become true.

  • within() — searches for elements inside a particular element.

For realistic user interactions, the companion package @testing-library/user-event is often recommended.

Remember: Jest and React Testing Library have different responsibilities. Jest runs and organizes tests, while React Testing Library helps you render and interact with React components.

Jest vs React Testing Library

Although these tools are frequently used together, they are not the same thing.

Feature

Jest

React Testing Library

Main purpose

Run and manage tests

Test React components through their rendered interface

Assertions

Provides matchers such as toBe()

Often used with Jest matchers

Component rendering

Not provided by Jest itself

Provides render()

DOM queries

Not its main responsibility

Provides screen and query functions

Mocking

Provides mocking utilities

Focuses on component testing

Best use

Test execution, assertions, mocks, and coverage

Testing component output and user interactions

They work together to create a practical testing workflow for React applications.

Step 1: Set Up a React Testing Environment

Before writing tests, you need a React project and the appropriate testing packages.

The exact setup depends on how your React application was created.

Option A: React Project Using Vite

If you're using React with Vite, Vitest is often the most straightforward testing choice because it integrates directly with Vite's configuration.

However, if your goal is specifically to learn Jest, you can configure Jest for a Vite-based React application. This generally requires additional configuration for JSX or TypeScript transformation, CSS imports, and module resolution.

For this guide, we'll use Jest with a React application configured to support Jest testing.

Install the required development dependencies:

npm install --save-dev jest jest-environment-jsdom \
  @testing-library/react @testing-library/jest-dom \
  @testing-library/user-event

If your project uses Babel to transform JSX, you can also install:

npm install --save-dev babel-jest \
  @babel/core @babel/preset-env @babel/preset-react

The configuration below assumes a JavaScript project using Babel and ES module imports.

Configure Babel

Create a babel.config.cjs file in your project root:

module.exports = {
  presets: [
    ["@babel/preset-env", { targets: { node: "current" } }],
    ["@babel/preset-react", { runtime: "automatic" }],
  ],
};

This configuration allows Babel to transform modern JavaScript and React JSX for the Jest environment.

If you're using TypeScript, you'll need a TypeScript-compatible transformation setup as well.

Configure Jest

Create a jest.config.cjs file:

module.exports = {
  testEnvironment: "jsdom",
  setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
  testMatch: [
    "**/?(*.)+(test|spec).[jt]s?(x)",
  ],
};

The jsdom environment provides a browser-like DOM for component tests.

Create jest.setup.js:

import("@testing-library/jest-dom");

This loads additional matchers that make DOM assertions easier to read.

For example, you can use toBeInTheDocument() to check whether an element appears in the rendered interface.

Important: The configuration shown is a starting point, not a universal setup for every React project. If you use Vite, Next.js, TypeScript, CSS modules, or path aliases, you may need framework-specific configuration. Next.js projects can often use the framework's recommended Jest setup.

Add a Test Script

In your package.json, add the following script:

{
  "scripts": {
    "test": "jest"
  }
}

Keep your existing scripts and add the test entry rather than replacing the entire scripts object.

You can now run:

npm test

Your environment is ready for the examples below.

Step 2: Write Your First React Component Test

Let's start with a simple React component.

Create Greeting.jsx:

export default function Greeting() {
  return <h1>Hello, Developer!</h1>;
}

The component displays a heading.

Now create Greeting.test.jsx in the same directory:

import { render, screen } from "@testing-library/react";
import Greeting from "./Greeting";

test("renders the greeting message", () => {
  render(<Greeting />);

  expect(
    screen.getByRole("heading", {
      name: "Hello, Developer!",
    })
  ).toBeInTheDocument();
});

Let's understand what's happening.

1. Import render() and screen

import { render, screen } from "@testing-library/react";

render() displays the component in the test environment, while screen helps you locate elements.

2. Render the component

render(<Greeting />);

This renders the Greeting component so the test can inspect its output.

3. Find the heading

screen.getByRole("heading", {
  name: "Hello, Developer!",
});

This looks for a heading with the accessible name Hello, Developer!.

4. Check that it exists

.toBeInTheDocument();

This matcher checks whether the element is present in the document.

Run the test:

npm test

If the component displays the expected heading, the test should pass.

Why Use getByRole()?

React Testing Library provides several query methods, including:

  • getByRole() — finds an element by its semantic role and, optionally, accessible name.

  • getByText() — finds an element by its text.

  • getByLabelText() — finds a form control through its label.

  • queryByRole() — returns null when an element isn't found instead of immediately throwing an error.

  • findByRole() — asynchronously waits for a matching element to appear.

Whenever practical, prefer queries that reflect how users and assistive technologies identify interface elements.

Step 3: Test Button Clicks and Component State

Most React applications contain interactive components such as buttons, dropdowns, and counters.

Let's test a counter component.

Create Counter.jsx:

import { useState } from "react";

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>

      <button onClick={() => setCount((current) => current + 1)}>
        Increment
      </button>
    </div>
  );
}

When the user clicks the button, the count increases by one.

Create Counter.test.jsx:

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import Counter from "./Counter";

test("increments the count when the button is clicked", async () => {
  const user = userEvent.setup();

  render(<Counter />);

  expect(screen.getByText("Count: 0")).toBeInTheDocument();

  await user.click(
    screen.getByRole("button", { name: "Increment" })
  );

  expect(screen.getByText("Count: 1")).toBeInTheDocument();
});

This test verifies two things:

  1. The initial count is zero.

  2. Clicking the button updates the displayed count to one.

Notice that we're not checking the component's internal state directly. We're checking the result that users see.

This is one of the most important principles of React component testing.

Why Use userEvent Instead of fireEvent?

Both userEvent and fireEvent can trigger interactions in tests.

However, userEvent generally provides a more realistic simulation of user actions. For example, typing into an input can involve several events, while a single fireEvent.change() dispatches a particular DOM event directly.

For most ordinary user interactions, start with userEvent.

Use fireEvent when you need to dispatch a specific event that isn't conveniently represented by a userEvent interaction.

Step 4: Test React Forms

Forms are an important part of many applications, including login pages, registration pages, checkout flows, and contact forms.

Let's test a basic login form.

Create LoginForm.jsx:

import { useState } from "react";

export default function LoginForm() {
  const [email, setEmail] = useState("");

  function handleSubmit(event) {
    event.preventDefault();

    if (!email.trim()) {
      return;
    }

    // Submit the form or call an application handler.
  }

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="email">Email</label>

      <input
        id="email"
        type="email"
        value={email}
        onChange={(event) => setEmail(event.target.value)}
      />

      <button type="submit">Submit</button>
    </form>
  );
}

This component contains a controlled email input and a submit button.

Now write a test:

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import LoginForm from "./LoginForm";

test("allows the user to enter an email address", async () => {
  const user = userEvent.setup();

  render(<LoginForm />);

  const emailInput = screen.getByRole("textbox", {
    name: "Email",
  });

  await user.type(emailInput, "developer@example.com");

  expect(emailInput).toHaveValue("developer@example.com");
});

This test checks whether the user can enter an email address and whether the input displays the expected value.

You can also test required-field validation, error messages, and successful submission. For a real application, consider passing a submission callback as a prop so you can verify that the form submits the correct data.

For example, a test could confirm that submitting a valid form calls the provided callback with the expected email address.

Security reminder: Frontend form validation improves usability, but it doesn't replace server-side validation. Your backend must independently validate incoming data and enforce authorization.

Step 5: Test Conditional Rendering

React components often display different content depending on props, state, or application data.

For example, a component may show a loading indicator while fetching data and display the results after the request succeeds.

Let's test a component that displays different messages based on a prop.

Create StatusMessage.jsx:

export default function StatusMessage({ isLoading }) {
  if (isLoading) {
    return <p role="status">Loading...</p>;
  }

  return <p>Data loaded successfully.</p>;
}

Now create StatusMessage.test.jsx:

import { render, screen } from "@testing-library/react";
import StatusMessage from "./StatusMessage";

test("shows a loading message when loading", () => {
  render(<StatusMessage isLoading={true} />);

  expect(screen.getByRole("status")).toHaveTextContent("Loading...");
});

test("shows the success message when loading is complete", () => {
  render(<StatusMessage isLoading={false} />);

  expect(
    screen.getByText("Data loaded successfully.")
  ).toBeInTheDocument();
});

These tests verify that the component displays the correct message for each prop value.

This approach is useful for testing:

  • Loading indicators.

  • Empty states.

  • Error messages.

  • Success notifications.

  • Conditional buttons.

  • Role-based interface elements.

For components with several possible states, write tests for the most important user-visible outcomes.

Step 6: Test Asynchronous Behavior

Many React components fetch information from APIs.

For example, a dashboard may retrieve a user's profile from a backend service and display the result when the request finishes.

Asynchronous behavior needs special attention because the expected content may not appear immediately.

Consider this component.

Create UserProfile.jsx:

import { useEffect, useState } from "react";

export default function UserProfile({ fetchUser }) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    let active = true;

    fetchUser().then((data) => {
      if (active) {
        setUser(data);
      }
    });

    return () => {
      active = false;
    };
  }, [fetchUser]);

  if (!user) {
    return <p role="status">Loading profile...</p>;
  }

  return <h1>{user.name}</h1>;
}

This example receives fetchUser as a prop. Passing the function in makes the component easier to test without requiring a real backend.

Create UserProfile.test.jsx:

import { render, screen } from "@testing-library/react";
import UserProfile from "./UserProfile";

test("displays the user name after the request completes", async () => {
  const fetchUser = jest.fn().mockResolvedValue({
    name: "Alex",
  });

  render(<UserProfile fetchUser={fetchUser} />);

  expect(screen.getByRole("status")).toHaveTextContent(
    "Loading profile..."
  );

  expect(
    await screen.findByRole("heading", { name: "Alex" })
  ).toBeInTheDocument();

  expect(fetchUser).toHaveBeenCalledTimes(1);
});

Let's examine the key parts.

jest.fn()

Creates a mock function that Jest can track.

mockResolvedValue()

Configures the mock function to return a promise that resolves with the supplied value.

findByRole()

Waits for the expected heading to appear, making it useful for asynchronous rendering.

The test verifies that the loading state appears, the user's name eventually renders, and the function is called.

In production applications, you should also consider request failures, cancellation, and component unmounting. Those cases deserve separate tests when they are relevant to your implementation.

Step 7: Test Components That Use API Data

Suppose a React component displays products retrieved from an API.

You generally don't want every component test to make a real network request. External requests can make tests slow, unreliable, and dependent on the availability of another service.

A practical approach is to isolate API calls and provide controlled responses during testing.

For example, you might create a product component that accepts product data through props:

export default function ProductList({ products }) {
  if (products.length === 0) {
    return <p>No products found.</p>;
  }

  return (
    <ul>
      {products.map((product) => (
        <li key={product.id}>{product.name}</li>
      ))}
    </ul>
  );
}

You can test it without calling an API:

import { render, screen } from "@testing-library/react";
import ProductList from "./ProductList";

test("renders the supplied products", () => {
  render({
    /* Intentionally not a valid React element */
  });
});

The previous example demonstrates a common design principle—separating data retrieval from rendering—but the test must render the actual component correctly.

Here's the complete test:

import { render, screen } from "@testing-library/react";
import ProductList from "./ProductList";

test("renders the supplied products", () => {
  render(
    <ProductList
      products={[
        { id: 1, name: "Laptop" },
        { id: 2, name: "Keyboard" },
      ]}
    />
  );

  expect(screen.getByText("Laptop")).toBeInTheDocument();
  expect(screen.getByText("Keyboard")).toBeInTheDocument();
});

test("shows an empty state when there are no products", () => {
  render(<ProductList products={[]} />);

  expect(screen.getByText("No products found.")).toBeInTheDocument();
});

These tests cover both the populated state and the empty state.

For a component that performs its own API requests, you can mock the API module or use a request-mocking tool to provide controlled responses. That allows you to test loading, success, and error behavior without depending on a live service.

Step 8: Measure Code Coverage

Passing tests are useful, but you may also want to understand how much of your code the tests execute.

Jest provides code coverage reporting.

Run:

npm test -- --coverage

Jest can report metrics such as:

  • Statements: The percentage of executable statements covered by tests.

  • Branches: The percentage of conditional paths exercised.

  • Functions: The percentage of functions called during testing.

  • Lines: The percentage of executable lines covered.

For example, if a component has separate loading, success, and error states, a test that covers only the success state may leave other branches untested.

Coverage reports help you identify gaps.

However, high code coverage does not automatically mean high-quality tests. A test can execute a line of code without verifying that it behaves correctly.

Focus on meaningful assertions and important user scenarios rather than chasing a percentage alone.

Step 9: Common Mistakes to Avoid

When starting with React component testing, watch out for these mistakes.

1. Testing Internal Implementation Details

Avoid making tests depend on private state variables or internal component methods.

Prefer checking the rendered interface and observable behavior.

2. Using Fragile Selectors

Selectors based on deeply nested DOM structures or implementation-specific class names can break when the UI changes.

Prefer accessible queries such as getByRole() and getByLabelText() when they fit the situation.

3. Forgetting to Await Asynchronous Interactions

When using userEvent or asynchronous queries, remember to use await where required.

Otherwise, a test may finish before the interaction or assertion completes.

4. Depending on Real APIs

Network requests can make tests unreliable if an external service is slow or unavailable.

Use mocks or controlled test data when the goal is to test a component's behavior independently.

5. Testing Only the Happy Path

Successful rendering is only one part of an application's behavior.

Depending on the component, consider testing empty states, invalid inputs, request failures, disabled buttons, and permission-related UI states.

6. Treating Snapshots as a Complete Testing Strategy

Snapshot tests can help detect unexpected rendering changes, but they don't prove that interactions or business logic work correctly.

Combine snapshots, where useful, with behavior-focused tests.

7. Ignoring Accessibility

Accessible roles and labels help users navigate interfaces with assistive technologies. They also make tests more representative of real usage.

Build accessibility into your components instead of treating it as an afterthought.

Best Practices for Testing React Components

To keep your tests reliable and maintainable, follow these guidelines:

  • Write tests for important user-visible behavior.

  • Use meaningful test descriptions.

  • Keep individual tests focused on clear outcomes.

  • Test success, loading, and error states when applicable.

  • Prefer accessible queries over fragile selectors.

  • Use realistic user interactions with userEvent.

  • Mock external dependencies when isolation is appropriate.

  • Keep tests independent of execution order.

  • Test important edge cases.

  • Run tests regularly during development.

  • Use coverage reports to identify gaps, not as the sole measure of quality.

You don't need to test every implementation detail. Prioritize behavior that matters to your users and the business logic your application depends on.

Conclusion

Testing React components with Jest and React Testing Library helps you detect bugs early and make changes with greater confidence.

Jest provides the test runner, assertions, mocks, and coverage tools. React Testing Library allows you to render components and verify how they behave from a user's perspective.

Start with simple components, then move on to interactions, forms, conditional rendering, asynchronous requests, and error states.

If you're building production applications with React, Next.js, or the MERN stack, automated testing is a valuable skill. It helps you catch regressions, maintain reliable features, and make your codebase easier to improve over time.

The best way to learn is to start small: choose one component in your current project, write a test for its expected behavior, and expand your test suite as the application grows.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘