Popular Searches
Popular Course Categories
Popular Courses

React Testing Library

React Testing Library

React Testing and Debugging

React Testing Library

React Testing Library (RTL) is a JavaScript testing library used to test React components by focusing on what users can see and do. It helps developers verify that components render the correct content, respond to user interactions, display validation messages, and handle loading and error states correctly.

React Testing Library encourages developers to write tests that resemble real user interactions instead of depending on a component's internal implementation details.

React JS Training Course: JustAcademy React JS Training Course

Course Demo: Register for React JS Course Demo


1. What Is React Testing Library?

React Testing Library is a lightweight testing utility that provides functions for rendering React components and interacting with their output in the DOM. It allows developers to locate elements, simulate user interactions, and verify the results.

It is built on top of DOM Testing Library and works with different JavaScript test runners. Jest and Vitest are commonly used alongside it, while React Testing Library provides the tools for rendering and querying React components.

Example

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

function Welcome() {
  return <h1>Welcome to React!</h1>;
}

test("displays the welcome message", () => {
  render(<Welcome />);
  expect(
    screen.getByRole("heading", { name: "Welcome to React!" })
  ).toBeInTheDocument();
});

In this example, the component is rendered, the heading is located by its accessible role and name, and an assertion verifies that the heading exists in the document.


2. Why Is React Testing Library Important?

Testing helps ensure that a React application behaves correctly before and after code changes. React Testing Library makes it easier to test components from the user's perspective.

  • Improves reliability: Helps identify problems before users encounter them.
  • Tests user-visible behavior: Verifies content, controls, messages, and interactions.
  • Supports reusable components: Allows individual components to be tested in isolation.
  • Encourages accessible interfaces: Promotes locating elements by roles, labels, and accessible names.
  • Reduces regression bugs: Helps detect when a code change breaks existing functionality.
  • Supports maintainability: Tests are less dependent on internal component implementation.
  • Tests interactive behavior: Verifies actions such as clicking buttons, typing in fields, and submitting forms.

3. React Testing Library vs. a Test Runner

React Testing Library is not itself a complete test runner. It works together with tools that execute tests and report their results.

Tool Purpose Example
React Testing Library Renders components and provides DOM queries. render(), screen.getByRole()
Jest Runs tests and provides test functions, mocks, and assertions. test(), jest.fn()
Vitest Provides a test runner and mocking tools, often used with Vite projects. describe(), vi.fn()
user-event Simulates realistic user interactions. user.click(), user.type()
jest-dom Adds useful DOM-specific matchers. toBeInTheDocument(), toBeDisabled()

The exact setup depends on the project's React version, bundler, and chosen test runner.


4. Installing React Testing Library

React Testing Library can be installed as a development dependency. The following setup is suitable for many React projects using npm.

Step 1: Install React Testing Library

npm install --save-dev @testing-library/react @testing-library/dom

Step 2: Install User Interaction Utilities

npm install --save-dev @testing-library/user-event

Step 3: Install DOM Matchers

npm install --save-dev @testing-library/jest-dom

Step 4: Install a Test Runner

If the project uses Jest, install and configure Jest with a DOM environment and a suitable JSX transformation setup. If the project uses Vite, Vitest is a common choice.

For a Vite project, a typical installation is:

npm install --save-dev vitest jsdom

Make sure the versions of React Testing Library, React, and the chosen test environment are compatible. The following example demonstrates a typical Vitest configuration.

Example: vite.config.js

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [react()],
  test: {
    environment: "jsdom",
    setupFiles: "./src/setupTests.js"
  }
});

If your Vite configuration file does not already include test-related TypeScript definitions, you may need a separate vitest.config.js or the appropriate configuration typing for your installed Vitest version.

Example: src/setupTests.js

import "@testing-library/jest-dom/vitest";

This setup file loads DOM matchers compatible with Vitest. For Jest, the usual setup import is import "@testing-library/jest-dom";.

Example: package.json Scripts for Vitest

{
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "test": "vitest",
    "test:run": "vitest run"
  }
}

Use the scripts appropriate for your existing project rather than replacing its entire configuration without checking it.


5. Important React Testing Library Functions

React Testing Library provides several functions for rendering components, finding elements, and testing changes in the UI.

Function Purpose
render() Renders a React element into a test DOM.
screen Provides queries for locating elements in the document.
getByRole() Finds one element by its accessible role and optional name.
getByText() Finds an element by its text content.
getByLabelText() Finds a form control using its associated label.
queryByRole() Returns a matching element or null if none is found.
findByRole() Waits for an element to appear and returns a Promise.
waitFor() Retries an assertion or callback until it succeeds or times out.
within() Limits queries to a specific part of the DOM.
cleanup() Unmounts rendered components; automatic cleanup is commonly configured by the testing environment.

6. Understanding render()

The render() function mounts a React component in a test DOM environment. Once the component is rendered, the test can inspect its visible output and interact with its elements.

Example

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

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

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

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

Here, render() creates the component's DOM output. The test then checks whether the expected heading appears.


7. Understanding screen

The screen object provides query methods that search the document for elements. It is generally recommended because tests can locate elements in the same document where a user would encounter them.

Example

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

function Profile() {
  return (
    <section>
      <h1>User Profile</h1>
      <p>Name: Aditi</p>
      <button>Edit Profile</button>
    </section>
  );
}

test("displays profile information", () => {
  render(<Profile />);

  expect(
    screen.getByRole("heading", { name: "User Profile" })
  ).toBeInTheDocument();

  expect(screen.getByText("Name: Aditi")).toBeInTheDocument();

  expect(
    screen.getByRole("button", { name: "Edit Profile" })
  ).toBeInTheDocument();
});

The test verifies three different parts of the rendered interface: a heading, a paragraph, and a button.


8. Query Methods in React Testing Library

Queries locate elements in the rendered DOM. The main query families are getBy, queryBy, and findBy. Choosing the correct query helps tests handle missing and asynchronously rendered elements correctly.

Query When to Use Behavior if No Match Exists
getBy... Element should already exist. Throws an error.
queryBy... Checking whether an element is absent. Returns null.
findBy... Element may appear asynchronously. Returns a Promise and rejects after its timeout.
getAllBy... One or more matching elements are expected. Throws if no matches exist.
queryAllBy... Zero or more matches may exist. Returns an empty array when no matches exist.
findAllBy... Multiple elements may appear asynchronously. Returns a Promise and rejects if no matches appear in time.

Example: getByRole()

render(<button>Save Changes</button>);

const button = screen.getByRole("button", {
  name: "Save Changes"
});

expect(button).toBeInTheDocument();

Example: queryByText()

render(<p>Welcome back!</p>);

expect(screen.queryByText("Error occurred")).not.toBeInTheDocument();

Example: findByText()

render(<AsyncMessage />);

expect(
  await screen.findByText("Data loaded successfully")
).toBeInTheDocument();

Use getBy for expected immediate content, queryBy for absence checks, and findBy for content that appears asynchronously.


9. Query Priority and Accessibility

React Testing Library recommends querying elements in ways that reflect how users perceive and interact with the interface. Accessible queries also help identify accessibility problems.

A useful general preference order is:

  1. getByRole() with an accessible name.
  2. getByLabelText() for form fields.
  3. getByPlaceholderText() when appropriate.
  4. getByText() for visible text.
  5. getByDisplayValue() for form values.
  6. getByAltText() for images and other elements with alternative text.
  7. getByTestId() when user-facing queries are unsuitable.

Example: Accessible Form Query

function LoginForm() {
  return (
    <form>
      <label htmlFor="email">Email Address</label>
      <input id="email" type="email" />
    </form>
  );
}

test("finds the email field by its label", () => {
  render(<LoginForm />);

  expect(screen.getByLabelText("Email Address"))
    .toBeInTheDocument();
});

The label connects the field to a meaningful accessible name. This benefits both users and tests.


10. Writing Assertions with jest-dom

Assertions verify whether the application's behavior matches the expected result. The @testing-library/jest-dom package adds readable matchers for checking DOM elements and their states.

Matcher Purpose
toBeInTheDocument() Checks whether an element is in the document.
toHaveTextContent() Checks an element's text content.
toBeVisible() Checks whether an element is visible.
toBeDisabled() Checks whether a form control is disabled.
toBeEnabled() Checks whether a form control is enabled.
toHaveValue() Checks the current value of a form control.
toBeChecked() Checks whether a checkbox or radio button is checked.
toHaveAttribute() Checks an element's attribute.

Example

render(
  <div>
    <p>Order confirmed</p>
    <button disabled>Processing</button>
  </div>
);

expect(screen.getByText("Order confirmed"))
  .toHaveTextContent("Order confirmed");

expect(screen.getByRole("button"))
  .toBeDisabled();

11. Testing User Interactions with user-event

The @testing-library/user-event package simulates user interactions such as clicking buttons, typing text, selecting options, and pressing keyboard keys. It is generally preferred over low-level event dispatch when testing common user actions.

Example: Testing a Button Click

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

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
}

test("increases the count when clicked", async () => {
  const user = userEvent.setup();
  render(<Counter />);

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

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

The test starts the counter, simulates a real-style click, and checks the updated value. The test verifies the result of the interaction rather than inspecting the component's internal state.


12. Testing Form Inputs

Forms are a common area for React Testing Library. Tests can check whether input fields accept values, buttons submit forms, and the correct response is displayed.

Example: Testing a Name Form

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

function NameForm() {
  const [name, setName] = useState("");
  const [submittedName, setSubmittedName] = useState("");

  function handleSubmit(event) {
    event.preventDefault();
    setSubmittedName(name);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="name">Your Name</label>
      <input
        id="name"
        value={name}
        onChange={(event) => setName(event.target.value)}
      />
      <button type="submit">Submit</button>
      {submittedName && (
        <p>Hello, {submittedName}!</p>
      )}
    </form>
  );
}

test("submits the entered name", async () => {
  const user = userEvent.setup();
  render(<NameForm />);

  await user.type(
    screen.getByRole("textbox", { name: "Your Name" }),
    "Aditi"
  );

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

  expect(screen.getByText("Hello, Aditi!"))
    .toBeInTheDocument();
});

This test verifies the complete user flow: entering a name, submitting the form, and seeing the personalized message.


13. Testing Conditional Rendering

Conditional rendering means displaying different UI content depending on a condition. Tests should verify the content shown for each relevant condition.

Example

function StatusMessage({ isLoggedIn }) {
  return (
    <div>
      {isLoggedIn
        ? <p>Welcome back!</p>
        : <p>Please log in.</p>}
    </div>
  );
}

test("shows the login message when logged out", () => {
  render(<StatusMessage isLoggedIn={false} />);

  expect(screen.getByText("Please log in."))
    .toBeInTheDocument();

  expect(screen.queryByText("Welcome back!"))
    .not.toBeInTheDocument();
});

The test checks both what should be present and what should be absent for the logged-out state.


14. Testing Loading and Error States

React components may display a loading message while data is being retrieved, an error message when an operation fails, or the resulting content after a successful operation. These states should be tested separately when they are important to the user experience.

Example: Loading State

function DataPanel({ loading, error, data }) {
  if (loading) {
    return <p>Loading data...</p>;
  }

  if (error) {
    return <p role="alert">Unable to load data.</p>;
  }

  return <p>{data}</p>;
}

test("shows a loading message", () => {
  render(<DataPanel loading={true} error={false} data="" />);

  expect(screen.getByText("Loading data..."))
    .toBeInTheDocument();
});

test("shows an error message", () => {
  render(<DataPanel loading={false} error={true} data="" />);

  expect(screen.getByRole("alert"))
    .toHaveTextContent("Unable to load data.");
});

This example tests the loading and error states by supplying different props. For components that perform real asynchronous requests, use appropriate mocks and asynchronous queries to verify the full workflow.


15. Testing Asynchronous Components

Some React components update after a Promise resolves, an API request completes, or a timer or event triggers a change. These tests need to wait for the expected UI to appear.

Example: Asynchronous Message

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

function AsyncMessage() {
  const [message, setMessage] = useState("");

  function loadMessage() {
    Promise.resolve("Data loaded successfully")
      .then(setMessage);
  }

  return (
    <div>
      <button onClick={loadMessage}>Load Data</button>
      {message && <p>{message}</p>}
    </div>
  );
}

test("displays data after loading", async () => {
  const user = userEvent.setup();
  render(<AsyncMessage />);

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

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

The findByText() query waits for the expected message to appear. This is useful when the UI changes asynchronously.


16. Understanding waitFor()

The waitFor() utility repeatedly runs a callback until it stops throwing an error or the timeout is reached. It is useful when an asynchronous assertion cannot be expressed conveniently with a findBy query.

Example

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

test("eventually enables the submit button", async () => {
  render(<AsyncForm />);

  const button = screen.getByRole("button", {
    name: "Submit"
  });

  await waitFor(() => {
    expect(button).toBeEnabled();
  });
});

AsyncForm in this example represents a component that enables its submit button after an asynchronous operation. In a real test, render that component and ensure the test setup matches its behavior.

Use findBy when waiting for an element to appear. Use waitFor when an assertion or condition needs to be retried. Avoid arbitrary delays such as setTimeout just to wait for the UI.


17. Testing Lists and Repeated Elements

React often renders lists using the JavaScript map() method. Tests can verify that the expected items appear in the rendered UI.

Example

function CourseList() {
  const courses = ["React JS", "JavaScript", "HTML"];

  return (
    <ul>
      {courses.map((course) => (
        <li key={course}>{course}</li>
      ))}
    </ul>
  );
}

test("displays all courses", () => {
  render(<CourseList />);

  expect(screen.getByText("React JS")).toBeInTheDocument();
  expect(screen.getByText("JavaScript")).toBeInTheDocument();
  expect(screen.getByText("HTML")).toBeInTheDocument();
});

This test verifies that each course is present in the rendered list. The key helps React identify list items between renders.


18. Testing Components That Receive Props

Props allow components to display different information based on the values they receive. Tests can render a component with particular props and verify that the expected output appears.

Example

function UserCard({ name, role }) {
  return (
    <article>
      <h2>{name}</h2>
      <p>Role: {role}</p>
    </article>
  );
}

test("renders the user details passed through props", () => {
  render(<UserCard name="Riya" role="Developer" />);

  expect(
    screen.getByRole("heading", { name: "Riya" })
  ).toBeInTheDocument();

  expect(screen.getByText("Role: Developer"))
    .toBeInTheDocument();
});

This test checks the component's output without depending on how the component stores or processes its props internally.


19. Using fireEvent vs. user-event

Both fireEvent and user-event can trigger interactions in tests, but they work at different levels.

Feature fireEvent user-event
Purpose Dispatches a specific DOM event. Simulates a higher-level user interaction.
Interaction detail Usually targets an individual event. May perform several events and checks for one action.
Typical usage fireEvent.change(input, ...) await user.type(input, "Hello")
Recommendation Useful for specific low-level events not covered by user-event. Generally preferred for common user actions.

Example: fireEvent

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

test("updates a field value", () => {
  render(
    <input aria-label="Search" defaultValue="" />
  );

  const input = screen.getByRole("textbox", {
    name: "Search"
  });

  fireEvent.change(input, {
    target: { value: "React" }
  });

  expect(input).toHaveValue("React");
});

For common typing and clicking workflows, prefer user-event. Use fireEvent when a test specifically needs to dispatch a lower-level DOM event.


20. Testing Best Practices

  • Test what users can see and do rather than the internal implementation.
  • Prefer accessible queries such as getByRole() and getByLabelText().
  • Use user-event for common user interactions.
  • Use findBy and waitFor for asynchronous UI changes when appropriate.
  • Write clear test names that explain the expected behavior.
  • Test important success, loading, empty, and error states.
  • Keep each test focused on one behavior or a closely related set of expectations.
  • Use mock functions or mock network requests when external services are not part of the test.
  • Avoid relying on internal state variables or private implementation details.
  • Use stable list keys in application code.
  • Keep test data readable and predictable.
  • Run tests regularly and after significant code changes.
  • Use test IDs only when more user-oriented queries are unsuitable.
  • Do not use arbitrary time delays to wait for UI changes.

21. Common Mistakes in React Testing Library

Mistake Problem Better Practice
Testing internal state directly Tests become tightly coupled to implementation details. Verify the visible result of the state change.
Using the wrong query A test may fail when an element is absent or appears asynchronously. Choose among getBy, queryBy, and findBy based on the situation.
Forgetting to await user interactions Assertions may run before the interaction finishes. Await asynchronous user-event methods.
Using arbitrary delays Tests become slow and unreliable. Use asynchronous queries or waitFor.
Overusing test IDs Tests may ignore accessible names and visible UI behavior. Prefer roles, labels, and visible text when appropriate.
Testing only the initial render Interactive bugs may remain undetected. Test important user actions and resulting states.
Mocking everything Tests may stop checking meaningful application behavior. Mock external dependencies where needed while testing the UI's actual behavior.

22. Practical Project: Testing a Login Form

In this mini-project, you will create a simple login form and write tests to check the form fields, user input, and submission behavior.

Step 1: Create LoginForm.jsx

import { useState } from "react";

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

  function handleSubmit(event) {
    event.preventDefault();
    setSubmitted(true);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="email">Email</label>
      <input
        id="email"
        type="email"
        value={email}
        onChange={(event) => setEmail(event.target.value)}
        required
      />
      <button type="submit">Log In</button>
      {submitted && <p role="status">Login submitted</p>}
    </form>
  );
}

Step 2: Create LoginForm.test.jsx

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

test("renders the email field and login button", () => {
  render(<LoginForm />);

  expect(screen.getByRole("textbox", { name: "Email" }))
    .toBeInTheDocument();

  expect(screen.getByRole("button", { name: "Log In" }))
    .toBeInTheDocument();
});

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

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

  await user.type(emailInput, "[email protected]");

  expect(emailInput).toHaveValue("[email protected]");
});

test("shows a confirmation after submission", async () => {
  const user = userEvent.setup();
  render(<LoginForm />);

  await user.type(
    screen.getByRole("textbox", { name: "Email" }),
    "[email protected]"
  );

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

  expect(screen.getByRole("status"))
    .toHaveTextContent("Login submitted");
});

Step 3: Run the Tests

npm test

For the Vitest script shown earlier, this runs Vitest in watch mode. To run tests once, use:

npm run test:run

Learning outcomes: You have practiced rendering a component, finding a form field by its label, simulating user input, clicking a button, and verifying the visible result.


23. React Testing Library Interview Questions and Answers

Q1. What is React Testing Library?

Answer: React Testing Library is a testing utility for React components that encourages tests based on user-visible behavior and DOM interactions.

Q2. Is React Testing Library a test runner?

Answer: No. It provides utilities for rendering and testing React components. A test runner such as Jest or Vitest executes the tests.

Q3. What does render() do?

Answer: It renders a React element into a test DOM so the test can inspect the resulting interface.

Q4. What is screen?

Answer: screen provides query methods for locating elements in the document, such as getByRole() and getByText().

Q5. What is the difference between getBy and queryBy?

Answer: A getBy query throws an error if no matching element exists, while queryBy returns null when no match is found.

Q6. What is the difference between getBy and findBy?

Answer: getBy checks for an element immediately, while findBy returns a Promise and waits for an element to appear.

Q7. Why is user-event useful?

Answer: It simulates common user interactions, such as typing and clicking, in a way that is closer to how users interact with the browser.

Q8. What is jest-dom?

Answer: It is a package that adds readable assertions for DOM elements, such as toBeInTheDocument() and toBeDisabled().

Q9. When should waitFor() be used?

Answer: Use it when an assertion needs to be retried until an asynchronous condition becomes true. For an element that appears asynchronously, a findBy query is often simpler.

Q10. Why should tests focus on user behavior?

Answer: User-focused tests verify meaningful application behavior and are less likely to break when internal implementation details change.

Q11. How can you test that an element is absent?

Answer: Use a query such as queryByText() and assert that the result is not in the document.

Q12. Can React Testing Library work with Vitest?

Answer: Yes. React Testing Library can be used with Vitest, provided the project has the appropriate test environment and setup.


24. Practice Exercises

  1. Write a test that checks whether a heading is rendered correctly.
  2. Test a button that increments a counter when clicked.
  3. Write tests for a form that accepts a name and displays a greeting.
  4. Test a component that displays a message based on a Boolean prop.
  5. Verify that a disabled button cannot be interacted with normally.
  6. Test whether a loading message appears while data is being retrieved.
  7. Test whether an error message appears when a request fails.
  8. Render a list of courses and verify that all expected items appear.
  9. Use findByRole() to wait for asynchronous content.
  10. Build and test a complete login form with validation and submission feedback.

25. Quick Revision Checklist

  • Understand the purpose of React Testing Library.
  • Know the difference between a testing utility and a test runner.
  • Understand how to install and configure testing dependencies.
  • Practice using render() and screen.
  • Understand the differences among getBy, queryBy, and findBy.
  • Use accessible queries to locate elements.
  • Practice user interactions with user-event.
  • Write assertions using DOM matchers.
  • Test forms, lists, props, conditional rendering, and asynchronous content.
  • Understand when to use waitFor().
  • Write tests that focus on user-visible behavior.
  • Run tests regularly and investigate failures before changing assertions.

26. Conclusion

React Testing Library is an important tool for developing reliable React applications. It helps developers test components by interacting with their rendered DOM in ways that resemble real user behavior. By learning how to render components, query accessible elements, simulate interactions, write assertions, and handle asynchronous changes, developers can create maintainable tests that help prevent regressions and improve application quality.

To continue learning React JS, explore the JustAcademy React JS Training Course or register for a React JS course demo.

Official Documentation and Resources

Previous Next
whatsapp