Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 30 ยท Testing Real Applications

Testing UI with jsdom and Testing Library

Test user interfaces in Jest with jsdom and Testing Library: query by role and accessible name, simulate user events, avoid brittle selectors, with browser stand-ins.

Most user interfaces are tested in one of two places: a real browser, or a fake one. A real browser (driven by Playwright or Cypress) is the most faithful, but it is slow. A fake browser is much faster. Jest ships with a way to use one: set testEnvironment: "jsdom", and your tests get a document, a window and the usual DOM APIs, all implemented in JavaScript inside Node.

jsdom does not draw pixels, run layout or play video. That is fine, because most UI tests ask structural questions: is there a button called "Save", does clicking it show a message, is the field marked invalid? Testing Library is the toolkit that helps you ask those questions in a way that survives refactoring. This lesson explains the approach and shows the main ideas with runnable stand-ins.

Real versus stand-in. The Jest and Testing Library code is real but read-only, because the site cannot install packages. The TryIt blocks run in your browser's own DOM with small hand-written helpers that imitate getByRole and click. They are stand-ins: Testing Library does far more (full ARIA role rules, async queries, helpful error output).

Test like a user

Find by what users see Role, label and visible text.
Act like a user Click, type, tab.
Check what they would notice Text, state, focus.

Avoid class names and component internals.

1 / 2

Setting up jsdom

Since Jest 28 the jsdom environment is a separate package. Install it with the helpers, then enable it:

Terminal
npm install --save-dev jest-environment-jsdom @testing-library/dom @testing-library/user-event @testing-library/jest-dom
JavaScript
// jest.config.js
module.exports = {
  testEnvironment: "jsdom",
  setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
};
JavaScript
// jest.setup.js
require("@testing-library/jest-dom");

The setup file adds DOM-aware matchers such as toBeInTheDocument(), toBeDisabled() and toHaveTextContent(). See Configuring Jest if those options are new.

If you use React, @testing-library/react adds render() on top of the same idea, and the same query functions come with it. The principles in this lesson do not depend on any framework.

A first DOM test

Suppose a small module builds a greeting form:

JavaScript
// greeting.js
export function mountGreeting(root) {
  root.innerHTML = `
    <label for="name">Your name</label>
    <input id="name" type="text">
    <button type="button">Greet</button>
    <p role="status"></p>
  `;
  const input = root.querySelector("input");
  const output = root.querySelector("[role=status]");
  root.querySelector("button").addEventListener("click", () => {
    output.textContent = input.value ? `Hello, ${input.value}!` : "Please type a name.";
  });
}

A Testing Library test looks like this:

JavaScript
import { screen } from "@testing-library/dom";
import userEvent from "@testing-library/user-event";
import { mountGreeting } from "./greeting";

test("greets the person by name", async () => {
  const user = userEvent.setup();
  mountGreeting(document.body);

  await user.type(screen.getByLabelText("Your name"), "Ada");
  await user.click(screen.getByRole("button", { name: "Greet" }));

  expect(screen.getByRole("status")).toHaveTextContent("Hello, Ada!");
});

Read it as a story: find the field by its label, type, click the button by its role and name, then look at the status message. Nothing in the test mentions a class name, an id or the HTML structure. If a designer swaps the <button> for a styled <a role="button"> or reorganizes the markup, the test still passes, because the behavior the user sees is unchanged.

Queries: getBy, queryBy, findBy

Testing Library names its queries with a prefix that tells you what happens when nothing matches:

Prefix No match More than one Use it for
getBy... throws throws An element that must exist now.
queryBy... returns null throws Asserting something is absent.
findBy... rejects after a wait rejects An element that appears later (async).

Add All (getAllByRole) to get an array. Use queryBy with not.toBeInTheDocument(), because getBy would throw before the assertion runs. Use findBy after a click that triggers a fetch; it polls until the element appears or a timeout passes, which fits the async patterns in Testing Promises and Async/Await.

Why roles?

Browsers and screen readers give every element a role (button, link, heading, textbox, checkbox...) and an accessible name (its label or text). Querying by role means your tests use the same information assistive technology uses. When getByRole("button", { name: "Greet" }) fails, it often means a real user would also struggle: the control has no accessible name, or it is not a button at all. Good tests double as a cheap accessibility check.

Stand-in 1: a tiny getByRole

The stand-in below finds elements by their implicit role and accessible name, using a small lookup table. Real implementations follow the full ARIA rules; this one only knows a handful of tags, but it shows the mechanism.

A toy getByRole

The email field was found by its label text, not by id or class. Asking for a button named "Delete" throws a helpful message, just like getBy in the real library.

Simulating user events

fireEvent.click(button) dispatches a single click event. userEvent goes further and imitates what a person does: user.click also moves the pointer and focuses the element, user.type sends a key press for each character, and user.tab moves focus. Prefer userEvent for realistic tests; it catches bugs such as a button that is visually covered or a field that is disabled.

The stand-in below dispatches real DOM events, which is what Testing Library does underneath.

Dispatching events and asserting

Two tests, written as small checks on what a user would see. Notice that the second check reuses the page the first one left behind. In a real Jest suite you would rebuild the DOM in beforeEach (see Test Isolation and Shared State) so tests cannot affect each other.

What not to test

  • Implementation details. Do not assert on component state, private methods or the exact number of divs.
  • Styles and layout. jsdom does not compute real layout. Use a real browser test for anything visual.
  • Library behavior. Do not test that the browser's <input> stores text; test your own logic.
  • Snapshots of whole pages. They fail for harmless reasons. Snapshot Testing explains when they are worth it.

jsdom also lacks some APIs (such as IntersectionObserver and matchMedia); the usual fix is a small mock in your setup file.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which package must you install in recent Jest versions to use testEnvironment: "jsdom"?

    Jest no longer bundles jsdom. Install jest-environment-jsdom and set testEnvironment to "jsdom".
  2. 2. You want to assert that an error message is NOT on the page. Which query is right?

    queryBy returns null when nothing matches, so the assertion can run. getBy would throw before it could.
  3. 3. Why prefer getByRole("button", { name: "Save" }) over document.querySelector(".btn-primary")?

    Roles and accessible names describe what users and assistive technology perceive, whereas class names are internal styling details.
  4. 4. A button appears after a fetch finishes. Which query waits for it?

    findBy queries return a promise that retries until the element shows up or a timeout passes.

Summary

  • testEnvironment: "jsdom" gives Jest tests a DOM; install jest-environment-jsdom for it.
  • Testing Library encourages tests that find elements the way users do: by role, label and visible text.
  • getBy throws, queryBy returns null, findBy waits; add All for several elements.
  • userEvent simulates realistic interaction better than raw fireEvent.
  • Test visible behavior, not implementation details, and use a real browser for layout and visuals.

Next, test code that talks to servers and storage in Testing APIs and Databases.