---
title: "Complete Guide to Unit Tests with React"
canonical: https://cesarfelipe.dev/articles/complete-guide-to-unit-tests-with-react/
published: 2022-04-29
updated: 2026-12-05
author: César Felipe
---

**TL;DR**

- Unit tests give you the confidence to change and refactor a React app without checking every screen by hand.
- Test components by behavior, not line coverage, with Jest and React Testing Library, and centralize setup in a makeSut helper.
- Simulate real interactions with user-event, wait for async state with findBy queries (and know what act does underneath), and test custom hooks with renderHook.
- Updated for React 18/19 and current Testing Library versions.

Have you ever been in a situation where a small change to the project was worrying because you didn’t know what could break? I guess everybody has been through this at least once. What we didn’t know back then was that we had a best friend: unit tests. Unit testing is an important topic, no matter which technology you use.

In this article, I want to dive into unit tests **(only unit tests)** in React apps.

## What are unit tests?

A unit test is a technique for testing a unit: the smallest piece of code that can be logically isolated in an application. It can be a function, a class method, a subroutine, etc. In our case, we will mostly test functions and React components.

## Why write unit tests?

As I said, unit tests are our best friend. They give us the confidence to make changes and refactor without worrying whether the application still works. They also make sure our code works properly, which avoids bugs and hours of debugging.

For example: there is a Link component that navigates inside the SPA through a `to` prop, and you add a new `href` prop for external links like youtube.com.

How do you make sure the `to` behavior still works and you didn’t break existing flows? Go screen by screen testing it? Ask other developers to check their screens? No: you write a unit test that guarantees that every click on a Link with a `to` prop navigates internally, and another test for the `href` behavior.

Before we practice, you need to know two tools: [Jest](https://jestjs.io/) and [React Testing Library](https://testing-library.com/docs/).

### Jest

Jest is a JavaScript/TypeScript testing framework: it runs the tests, checks coverage, supports mocks and more. Jest is awesome; if you don’t know it yet, visit the docs after finishing this article.

### React Testing Library

React Testing Library gives you superpowers to test your React apps. Jest is framework-agnostic and doesn’t care which framework you use, so React Testing Library handles React for us and makes our life easier.

## Setting up the project

I’ll create a new React project with `npx create-react-app unit-tests-tutorial --template typescript`. create-react-app uses Jest and React Testing Library by default, so no configuration is needed.

> **2026 note:** the React team [deprecated Create React App](https://react.dev/blog/2025/02/14/sunsetting-create-react-app) in February 2025. For a new project today I’d start with Vite and add Vitest (or Jest) with a jsdom environment and `@testing-library/jest-dom`. Everything in this article still applies: with Vitest, `jest.fn()` becomes `vi.fn()` and the rest of the tests barely change.

The examples use two more packages. Since React Testing Library v16, `@testing-library/dom` is a peer dependency, so you install it yourself, and `user-event` is the library I use to simulate interactions (more on it below):

```text
yarn add -D @testing-library/react @testing-library/dom @testing-library/user-event @testing-library/jest-dom
```

Now, let’s clean up the project structure and remove unnecessary files.

```text
unit-tests-tutorial/
├── node_modules/
├── public/
├── src/
│   ├── components/
│   │   └── button/
│   │       └── button.tsx
│   ├── App.tsx
│   ├── index.tsx
│   └── setupTests.ts
├── .gitignore
├── package.json
├── package-lock.json
├── README.md
└── tsconfig.json
```

*New project structure*

## How to test a simple UI component

I created a simple button component that receives two props: `label` and `onClick`.

*button.tsx*

```tsx
export interface ButtonProps {
  label: string;
  onClick: () => void;
}

export const Button = ({ label, onClick }: ButtonProps) => {
  return <button onClick={onClick}>{label}</button>;
};
```

Let’s write two simple tests: check that the label is rendered and that the `onClick` callback is called.

*button.test.tsx*

```tsx
import { Button, ButtonProps } from "./button";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

const makeSut = (props: Partial<ButtonProps>) => {
  return render(<Button label="label" onClick={jest.fn()} {...props} />);
};

describe("<Button />", () => {
  test("Should render label correctly", () => {
    makeSut({ label: "My Button" });

    expect(screen.getByRole("button", { name: "My Button" })).toBeInTheDocument();
  });

  test("Should call onClick successfully", async () => {
    const user = userEvent.setup();
    const spy = jest.fn();

    makeSut({ onClick: spy });

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

    expect(spy).toHaveBeenCalledTimes(1);
  });
});
```

### Why a makeSut helper keeps tests clean

I want you to focus on the `makeSut` ([SUT — System Under Test](https://stackoverflow.com/questions/7321407/what-is-sut-and-where-did-it-come-from)) function. I always use it, in frontend and backend tests alike. When you centralize the actor (Button), your tests are cleaner and easier to change, and each test can focus on the behavior it checks.

There are three things from Testing Library to learn here:

-   `render` renders the component in a container. It also returns query helpers, but today I query through `screen`, which is bound to `document.body`, so the test doesn’t care about what `render` returned.
-   `screen.getByRole` finds elements the way a user (or a screen reader) does: “the button called My Button”. If that query can’t find your element, there is a good chance a real user can’t either.
-   `userEvent` simulates a full interaction instead of a single DOM event. A click goes through pointer down, mouse down, focus, pointer up, mouse up and click, and it refuses to click an element with `pointer-events: none`. Since v14, every call returns a promise, so you create a `user` with `userEvent.setup()` before rendering and `await` each interaction.

`fireEvent` from `@testing-library/react` still exists, and it dispatches exactly the one event you ask for (click, change, submit, blur…). It’s fine for edge cases, but `user-event` catches bugs that `fireEvent` hides, like a focus or blur handler that never runs, or an input mask that works when `fireEvent.change` sets the whole value at once but breaks when a user types one character at a time. The `act` function matters too, but I’ll show it later.

Running `yarn test` gives the following result.

```text
 PASS  src/components/button/button.test.tsx
  <Button />
    ✓ Should render label correctly (21 ms)
    ✓ Should call onClick successfully (6 ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        0.645 s, estimated 1 s
Ran all test suites related to changed files.
```

*test result*

Both tests are passing. We ensured that the two behaviors of our component are working correctly.

## Testing a component with state: behavior over coverage

Now, let’s create a component a little more complex than a button.

*dropdown-list.tsx*

```tsx
import { useState } from "react";
import { Button } from "../button/button";

export interface DataItem {
  value: string;
  label: string;
}

export interface DropdownListProps {
  data: DataItem[];
  onRemoveItem: (item: DataItem, index: number) => void;
  labels: {
    show: string;
    hide: string;
  };
}

export const DropdownList = ({ data, onRemoveItem, labels }: DropdownListProps) => {
  const [dropdownOpened, setDropdownOpened] = useState(false);

  const onToggleVisibility = () => setDropdownOpened(opened => !opened);

  return (
      <div>
        <Button onClick={onToggleVisibility} label={dropdownOpened ? labels.hide : labels.show }/>

        {dropdownOpened && (
            <ul>
              {data.map((item, index) => (
                  <li key={item.value}>
                    {item.label}

                    <button onClick={() => onRemoveItem(item, index)}>Remove</button>
                  </li>
              ))}
            </ul>
        )}
      </div>
  );
};
```

The DropdownList component uses the Button component and renders a list of elements depending on its state. Pretty simple. This is how it looks:

![DropdownList in two states: closed on initial render, showing only a "Show Data" button; after one click the button reads "Hide Data" and a list of Item 1 to Item 5 appears, each with a Remove button. Clicking again closes it.](https://cesarfelipe.dev/_astro/dropdown-list-states.CfvI2bN7.svg)

*Dropdown list component*

The nice part: we put the Button component inside DropdownList and don’t need to worry whether it works. Its behavior is already tested. Now, let’s list the behaviors this component has and test them.

### Focus on behavior, not line coverage: you can cover a line without covering a behavior

-   Check if list is hidden on initial render
-   Check if list is visible after one click on the button
-   Check if button labels are changing
-   Check if all items have been rendered correctly
-   Check if the remove callback is being called with correct values

So, let’s test it.

*dropdown-list.test.tsx*

```tsx
import { DropdownList, DropdownListProps } from "./dropdown-list";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

const labels = {
  hide: "Hide",
  show: "Show"
};

const data = [
  { value: "1", label: "Item 1" },
  { value: "2", label: "Item 2" },
  { value: "3", label: "Item 3" },
];

const makeSut = (props: Partial<DropdownListProps>) => {
  return render(
      <DropdownList
          data={data}
          labels={labels}
          onRemoveItem={jest.fn()}
          {...props}
      />
  );
};

describe("<DropdownList />", () => {
  test("Should not render ul component on initial render", () => {
    makeSut({});

    expect(screen.queryByRole("list")).not.toBeInTheDocument();
  });

  test("Should render ul component when click on button", async () => {
    const user = userEvent.setup();
    makeSut({});

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

    expect(screen.getByRole("list")).toBeInTheDocument();
  });

  test("Should switch button label on click", async () => {
    const user = userEvent.setup();
    makeSut({});

    expect(screen.getByRole("button", { name: labels.show })).toBeInTheDocument();

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

    expect(screen.getByRole("button", { name: labels.hide })).toBeInTheDocument();
  });

  test("Should render 3 li correctly", async () => {
    const user = userEvent.setup();
    makeSut({});

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

    expect(screen.getAllByRole("listitem")).toHaveLength(data.length);
  });

  test("Should call onRemoveItem callback correctly", async () => {
    const user = userEvent.setup();
    const onRemoveItem = jest.fn();

    makeSut({ onRemoveItem });

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

    await user.click(screen.getAllByRole("button", { name: "Remove" })[2]);

    expect(onRemoveItem).toHaveBeenCalledWith(data[2], 2);
  });
});
```

A few nice things:

-   `getBy*` throws when the element isn’t there, so it’s the query for “this must exist”. `queryBy*` returns `null` instead, which is why the first test uses `queryByRole` to assert that the list is **not** rendered.
-   The `list` and `listitem` roles come for free from `ul` and `li`. I don’t need a `data-testid` or a `container.querySelector`, and if someone swaps the markup for a pile of `div`s, the test tells me the list stopped being a list for assistive technology.
-   `jest.fn` in the last test works as a spy: it knows whether the function was called, how many times, with which arguments, and much more. It’s great for mocking a dependency.

Again, we used `makeSut` to prepare the actor (DropdownList) and keep the tests focused on behavior. Running `yarn test` again, all tests pass.

```text
$ react-scripts test
 PASS  src/components/button/button.test.tsx
 PASS  src/components/dropdown-list/dropdown-list.test.tsx

Test Suites: 2 passed, 2 total
Tests:       7 passed, 7 total
Snapshots:   0 total
Time:        1.111 s
```

*test results*

## Testing asynchronous state updates with act

Let’s create the App container that uses the DropdownList component.

*App.tsx*

```tsx
import { useEffect, useState } from "react";

import { DataItem, DropdownList } from "./components/dropdown-list/dropdown-list";

const fakeApiCall = (): Promise<DataItem[]> => {
  return new Promise(resolve => {
    resolve([
      { value: "1", label: "Item 1" },
      { value: "2", label: "Item 2" },
      { value: "3", label: "Item 3" },
      { value: "4", label: "Item 4" },
      { value: "5", label: "Item 5" },
    ]);
  });
};

function App() {
  const [data, setData] = useState<DataItem[]>([]);

  useEffect(() => {
    fakeApiCall().then(data => {
      setData(data);
    });
  }, []);

  return (
    <DropdownList
        data={data}
        onRemoveItem={() => {}}
        labels={{ show: "Show Data", hide: "Hide Data" }}
    />
  );
}

export default App;
```

This component makes a fake API call and updates its state, which it passes to DropdownList. Let’s add a simple test that checks the “Show Data” button is there when the screen opens.

*App.test.tsx*

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

const makeSut = () => {
  return render(<App />);
};

describe("<App />", () => {
  test("Should render the Show Data button", () => {
    makeSut();

    expect(screen.getByRole("button", { name: "Show Data" })).toBeInTheDocument();
  });
});
```

Let’s run `yarn test`, and we get a surprise.

```text
...
This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
    at App (/home/user/project/src/App.tsx:18:27)

  20 |   useEffect(() => {
  21 |     fakeApiCall().then(data => {
> 22 |       setData(data);
     |       ^
  23 |     });
  24 |   }, []);
  25 |

  at printWarning (node_modules/react-dom/cjs/react-dom.development.js:86:30)
  at error (node_modules/react-dom/cjs/react-dom.development.js:60:7)
  at warnIfUpdatesNotWrappedWithActDEV (node_modules/react-dom/cjs/react-dom.development.js:27543:9)
  at scheduleUpdateOnFiber (node_modules/react-dom/cjs/react-dom.development.js:25404:5)
  at setData (node_modules/react-dom/cjs/react-dom.development.js:17389:16)
  at src/App.tsx:22:7

Test Suites: 3 passed, 3 total
Tests:       8 passed, 8 total
Snapshots:   0 total
Time:        1.569 s
```

*test result with error*

Our test passes, but it logs an error. How do we fix it? Suppressing the error would probably work, but this time we need to fix the actual problem. It happens because the component updates its state asynchronously: the test finished without waiting for `fakeApiCall` to resolve, so `setData` ran after the test had stopped looking, outside of React’s `act`. The warning is React telling you that your assertions ran against a screen the user would never see for more than a tick.

The way to read it: **the test isn’t waiting for the thing it should be testing.** So the fix is not to silence the warning but to assert on the state the user actually ends up with, the five items, and let Testing Library wait for it.

*App.test.tsx*

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

const makeSut = () => {
  return render(<App />);
};

describe("<App />", () => {
  test("Should render data", async () => {
    const user = userEvent.setup();
    makeSut();

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

    expect(await screen.findAllByRole("listitem")).toHaveLength(5);
  });
});
```

That’s it. `findAllByRole` is `getAllByRole` plus retries: it polls until the items show up (or fails after a timeout, one second by default), so the test waits for `fakeApiCall` to resolve and for the re-render. Running `yarn test`, everything is back to normal.

```text
 PASS  src/components/button/button.test.tsx
 PASS  src/App.test.tsx
 PASS  src/components/dropdown-list/dropdown-list.test.tsx

Test Suites: 3 passed, 3 total
Tests:       8 passed, 8 total
Snapshots:   0 total
Time:        1.553 s
Ran all test suites related to changed files.
```

*test results*

### So where is act?

Remember the `act` function I mentioned? It’s still there, you just don’t see it. `act` is the React API that says “run this, then flush every state update and effect it caused before I look at the DOM”. React Testing Library already wraps `render`, `fireEvent`, `user-event` interactions and the `findBy*`/`waitFor` helpers in it, which is why the test above needs no explicit `act`.

When there is nothing on screen to wait for, you can call it yourself:

```tsx
import { act } from "@testing-library/react";

await act(async () => {
  makeSut();
});
```

The `async` callback lets React flush the updates from promises that resolve right away, like our `fakeApiCall`. It does **not** wait for timers or real network requests, so for those you want `findBy*`/`waitFor`, fake timers, or a mocked API. My rule of thumb:

-   Something changes on screen? Use `findBy*` or `waitFor` and assert on it.
-   Testing a hook with no UI? Wrap the call in `act` (next section).
-   Still getting the warning? Something updates after your last assertion. Find it and wait for it; don’t wrap random lines in `act` until the console is quiet.

On React 19, `act` lives in `react` itself (`import { act } from "react"`), and the old `act` from `react-dom/test-utils` is deprecated. If you import `act` from `@testing-library/react`, it already picks the right one.

## How to test custom hooks

You’re probably thinking

> Cool, but we are on React 18, we use a lot of hooks, how to test it?

Testing hooks used to be tedious: you had to wrap the hook in a fake component, simulate a button click that called the function you needed, and read the result. I hated it, and so did the Testing Library maintainers, so they created a library to help: [react-hooks-testing-library](https://react-hooks-testing-library.com/) (`@testing-library/react-hooks`).

With React 18, `renderHook` moved into `@testing-library/react` itself (since v13.1), and the separate package was built for React 16 and 17: its maintainers point React 18 users to `@testing-library/react`. If you still have `@testing-library/react-hooks` in your `package.json`, switch the imports and uninstall it. There is nothing new to install.

I’ll create the classic useCounter hook just as a simple example:

*use-counter.ts*

```ts
import { useCallback, useState } from "react";

export const useCounter = () => {
  const [state, setState] = useState(0);

  const increment = useCallback(() => setState(state => state + 1), []);

  const decrement = useCallback(() => setState(state => state - 1), []);

  return {
    state,
    increment,
    decrement
  };
};
```

The `useCounter` hook has one state value and two methods. How do we make sure it works correctly?

*use-counter.test.ts*

```ts
import { act, renderHook } from "@testing-library/react";

import { useCounter } from "./use-counter";

const makeSut = () => {
  return renderHook(() => useCounter());
};

describe("useCounter()", () => {
  test("Should return 0 on initial state", () => {
    const { result } = makeSut();

    expect(result.current.state).toBe(0);
  });

  test("Should increment 1", () => {
    const { result } = makeSut();

    act(() => {
      result.current.increment();
    });

    expect(result.current.state).toBe(1);
  });

  test("Should decrement 1", () => {
    const { result } = makeSut();

    act(() => {
      result.current.decrement();
    });

    expect(result.current.state).toBe(-1);
  });
});
```

Very simple: the `renderHook` function “renders” the hook and gives us its state and methods. Calling `increment` updates state outside of any render, so that’s the case where I wrap the call in `act` myself.

`renderHook` is very handy. It accepts a `wrapper` in case your hook needs something like a context provider, and `initialProps` if you want to pass values to your hook and change them later with `rerender`. The returned values live inside a ref called `result`, and `renderHook` also returns `unmount` and `rerender` functions.

```tsx
const { result, rerender } = renderHook(({ step }) => useCounter(step), {
  initialProps: { step: 1 },
  wrapper: ({ children }) => <ThemeProvider>{children}</ThemeProvider>,
});

rerender({ step: 10 });
```

(This one assumes a `useCounter(step)` variant and some `ThemeProvider` in your app; the point is the shape of the options. Because of the JSX in the wrapper, the file needs to be `.tsx`.)

If you are migrating from `@testing-library/react-hooks`, two things bite. First, `waitForNextUpdate` doesn’t exist in `@testing-library/react`: use `await waitFor(() => expect(result.current.state).toBe(…))` instead. Second, `result.error` is gone, so a hook that should throw is tested with `expect(() => renderHook(() => useMyHook())).toThrow()`, and React will log the error to the console, which you may want to silence with a `jest.spyOn(console, "error")` in that test.

That’s basically how we test our hooks.

## Key takeaways

-   Unit tests let you change and refactor with confidence instead of re-checking every screen by hand.
-   A `makeSut` helper centralizes how the component under test is rendered, so each test only states the behavior it checks.
-   `render`, `screen` queries by role and `user-event` (v14, `await` every interaction) are enough to fully test most components.
-   Test behaviors, not lines: list what the component does (initial state, toggling, labels, callbacks) and write one test per behavior.
-   An act warning means something updated after the test stopped looking: wait for it with `findBy*` or `waitFor` instead of silencing it, and reach for `act` directly only when there is no UI to wait for.
-   Test custom hooks with `renderHook` from `@testing-library/react`; the separate `@testing-library/react-hooks` package belongs to the React 16/17 era.

I hope you enjoyed the content and learned something. There is a lot more to say about unit testing, like when to mock or spy on a dependency, but that can be another article.
