Test React components through the UI

19.3

Write a test that uses a component the way a person would use it, then assert what appears on screen.

On this page

Set up Vitest and Testing Library

In a React and Vite project, install the DOM environment and the testing libraries. The environment comment in the test below enables jsdom for that file. The cleanup hook removes the rendered component after each test.

npm install -D vitest jsdom @testing-library/react @testing-library/dom @testing-library/user-event
npx vitest run

Click and check the visible output

Find the button by its role and accessible name. Await the user action, then assert the new status text. Save this example as quantity.test.jsx. For network work, wait for the changed UI and cover both a successful response and a failure.

// @vitest-environment jsdom
import React, { useState } from "react";
import { afterEach, expect, test } from "vitest";
import { cleanup, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

afterEach(cleanup);

function Quantity() {
  const [quantity, setQuantity] = useState(0);
  return (
    <>
      <button onClick={() => setQuantity(value => value + 1)}>Add one</button>
      <p role="status">{quantity}</p>
    </>
  );
}

test("adds one to the visible quantity", async () => {
  const user = userEvent.setup();
  render(<Quantity />);
  await user.click(screen.getByRole("button", { name: "Add one" }));
  expect(screen.getByRole("status").textContent).toBe("1");
});

Official references