Component Testing

Component testing tests one UI component (a piece of the interface, a React component for example) on its own. With Testing Library, render() draws the…

You've just changed the newsletter form at the very bottom of your app. Checking it by hand means starting the app, logging in, scrolling down, typing an email, then clicking Send. There's a shorter way: test the component on its own.

That's component testing: one UI component is tested on its own, without running the whole app. A component is a piece of the interface you can reuse, for example a React component (a function that returns what to show). The component is rendered (drawn) into a fake DOM. Then the test types and clicks like a user and checks what appears. Picture testing one lift button in the workshop before it goes into the building. You press it exactly like a passenger would, then see whether its light comes on. You don't take the wiring apart. In this picture, the lift button is the component, the building is the whole app, and the light that comes on is what appears on the screen. The wiring inside the button is the component's insides, which the test doesn't touch.

Render, then search through screen

There are three tools. Vitest is the test runner. jsdom is the fake DOM (a pretend browser inside Node). Testing Library is a library that renders components and finds elements the way a user finds them. Another option is Vitest Browser Mode with the vitest-browser-react package, which runs tests in a real browser instead of jsdom. For jsdom and Testing Library, install these packages:

npm install -D @testing-library/react @testing-library/user-event @testing-library/jest-dom jsdom

In vitest.config.js, write test: { environment: "jsdom", setupFiles: ["./src/setup.js"] }. Then put import "@testing-library/jest-dom/vitest"; in the setup file src/setup.js. That line adds DOM matchers such as toBeInTheDocument(). Also add import { afterEach } from "vitest";, import { cleanup } from "@testing-library/react"; and afterEach(() => cleanup());. Testing Library only cleans up the DOM by itself when afterEach is a global, which means it can be used with no import. In Vitest, that is true only with the setting globals: true, which is off by default. So without these three lines, what one test rendered stays on the screen for the next test.

The example in this lesson is a newsletter form with an Email field and a Send button. The Lab uses the same form with Indonesian text: the button says Kirim (Send), and the thank-you starts with Terima kasih (Thank you). This is the component:

// SubscribeForm.jsx
import { useState } from "react";

export function SubscribeForm() {
  const [email, setEmail] = useState("");
  const [sent, setSent] = useState(false);

  return (
    <div>
      <label htmlFor="email">Email</label>
      <input id="email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
      <button type="button" onClick={() => setSent(true)}>Send</button>
      {sent && <p>{`Thank you, ${email}!`}</p>}
    </div>
  );
}

This component keeps what is typed in the Email field in email. When Send is clicked, sent becomes true, and only then does the thank-you appear. And this is the test:

// SubscribeForm.test.jsx
import { describe, it, expect } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { SubscribeForm } from "./SubscribeForm";

describe("SubscribeForm", () => {
  it("shows a thank-you after the email is sent", async () => {
    const user = userEvent.setup();
    render(<SubscribeForm />);

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

    expect(screen.getByText("Thank you, [email protected]!")).toBeInTheDocument();
  });
});

This test never touches email or sent inside the component. Both are state, data the component keeps with useState. The test only checks what the user sees. If the component's insides are rewritten but it looks the same, the test still passes.

Find elements the way a user finds them

Testing Library calls its element-finding functions queries. It ranks its queries from the most recommended. The higher up, the closer to how a user (and a screen reader, a program that reads the page aloud) finds an element:

  1. getByRole: by the element's role (button, textbox, link, heading, checkbox) and name. Try this first.
  2. getByLabelText: for form fields that have a label.
  3. getByPlaceholderText: when there's no label (there should be one).
  4. getByText: for plain text, paragraphs, messages.
  5. getByDisplayValue: by the value inside a form field. Then getByAltText and getByTitle, for special cases.
  6. getByTestId: the last resort, through a data-testid attribute.

{ name: "Send" } in getByRole is the name a screen reader reads out: the text inside the button, its label, or an aria-label attribute.

One question before you read on. The button <button>Send</button> is swapped for a <div onClick={...}>Send</div> that looks exactly the same. A test that searches with getByText("Send") still passes. Does one that searches with getByRole("button", { name: "Send" }) pass or fail?

A <div onClick> has no button role: it can't be focused with Tab, can't be pressed with Enter, and a screen reader doesn't know it's a button. So getByRole fails, with this message:

TestingLibraryElementError: Unable to find an accessible element with the role "button" and name "Send"

Here are the accessible roles:

  textbox:

  Name "Email":
  <input
    id="email"
    type="email"
    value="[email protected]"
  />

Meanwhile getByText("Send") still passes because the text is there. The test is green while the button is broken for keyboard users. So getByRole tests accessibility at the same time: whether everyone can use the page.

getBy, queryBy, findBy

Every query comes in three forms. The difference is what happens when the element isn't found:

Form When not found Async? Used for
getBy... throws an error no an element that must be there now
queryBy... returns null no making sure an element is not there
findBy... retries until a time limit (1 second), then errors yes, with await an element that appears later

Examples of queryBy and findBy:

// Before the button is clicked, the thank-you isn't there yet
expect(screen.queryByText("Thank you, [email protected]!")).toBeNull();

// An element that appears once a fetch is done
const name = await screen.findByText("Budi Santoso");

getByText for an element that isn't there throws an error right away, so the test stops on that line. To make sure something is not shown, use queryBy.

userEvent or fireEvent

There are two ways to trigger an interaction:

The difference shows when there's a bug. Say the Email field accidentally gets maxLength={5} (at most 5 letters). A real user can only type budi@. user.type also stops at budi@, so the page shows "Thank you, budi@!" and the test above fails, as it should. fireEvent.change puts [email protected] in directly and ignores the limit. So a test that uses fireEvent passes, and the bug is not caught. That's why userEvent is recommended: its interaction is closer to a real user.

⚠️ What makes component tests misleading

TL;DR: Component testing tests one UI component (a piece of the interface, a React component for example) on its own. With Testing Library, render() draws the component into a fake DOM (jsdom, a pretend browser inside Node). Then you use screen (the whole test page) to find elements the way a user finds them: getByRole first (the element's role and name, which tests accessibility too), then getByLabelText, getByText, and getByTestId last. getBy throws when nothing is found, queryBy returns null (to make sure an element is absent), and findBy waits for an element that appears later. userEvent is recommended over fireEvent. fireEvent sends only one event (a signal from the browser, such as "clicked"), while userEvent copies the series of events a real user makes. So a bug like a wrong maxLength (a limit on the number of letters) gets caught.

⚡ Render, then search through screen

Write:

const user = userEvent.setup();
render(<SubscribeForm />);

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

expect(screen.getByText("Thank you, [email protected]!")).toBeInTheDocument();

Meaning: Component testing tests one component (a piece of the interface) on its own, here SubscribeForm, a form with an Email field and a Send button. render from Testing Library puts the component into a fake DOM (a pretend browser inside Node), and every search starts from screen (the whole test page). user from userEvent.setup() types and clicks like a user. The test then checks what is visible on the screen, not the component's insides.

⚡ getByRole first

Guess first: <button>Send</button> is swapped for a <div onClick>Send</div> that looks the same. Does a test with getByRole("button", { name: "Send" }) (find an element with the button role and the name Send) pass or fail?

It fails. A <div onClick> has no button role, so it can't be focused with Tab and a screen reader (a program that reads the page aloud) doesn't recognise it. getByText("Send") still passes.

Meaning: getByRole finds an element by its role, the way a screen reader does. So getByRole tests accessibility (whether everyone can use the page) at the same time, and you try this query (an element-finding function) first. getByTestId comes last.

⚡ userEvent, not fireEvent

Meaning: userEvent sends the series of events (signals from the browser, such as "clicked") that happen when a real person types and clicks, so its interaction is more realistic. If the Email field accidentally gets maxLength={5} (at most 5 letters), user.type stops at budi@ and the test fails, as it should. fireEvent.change sends only one event and puts all the letters in at once, so the bug is not caught.

What you will learn