Skip to content
ClapelloNotes by Barath
ReactCh 13 · 4/6
Core4 min readUpdated

React / 73

render, screen and queries: finding things like a user

TL;DR

render puts a component into the fake DOM, screen finds elements in it, and jest-dom matchers check them. Reach for getByRole first.

The component

src/components/DishCard.jsx
export default function DishCard({ dish }) {
  return (
    <article>
      <img src={dish.image} alt={dish.name} />
      <h3>{dish.name}</h3>
      <p>₹{dish.price}</p>
      <button>Add {dish.name}</button>
    </article>
  );
}

The test

src/components/DishCard.test.jsx
import { render, screen } from "@testing-library/react";
import DishCard from "./DishCard";
 
const dish = { name: "Masala Dosa", price: 120, image: "/dosa.jpg" };
 
test("shows the dish and an add button", () => {
  render(<DishCard dish={dish} />);
 
  expect(screen.getByRole("heading", { name: "Masala Dosa" })).toBeInTheDocument();
  expect(screen.getByText("₹120")).toBeInTheDocument();
  expect(screen.getByRole("button", { name: "Add Masala Dosa" })).toBeEnabled();
  expect(screen.getByAltText("Masala Dosa")).toHaveAttribute("src", "/dosa.jpg");
});
  • render(<DishCard />) mounts the component into jsdom's document.body.
  • screen queries the whole document. Prefer it over the values render returns: one import, and it always looks at the current page.
  • Queries like getByRole return a real DOM element. jest-dom matchers like toBeInTheDocument() check it.

Which query? Ask what the user sees

accessible to everyone · use these first

  1. 1

    ByRole

    buttons, links, headings, inputs: getByRole("button", { name: "Add" })

  2. 2

    ByLabelText

    form fields with a <label>

  3. 3

    ByPlaceholderText

    only if there's no label

  4. 4

    ByText

    paragraphs, spans, divs (non-interactive text)

  5. 5

    ByDisplayValue

    the current value of a filled-in input

semantic

  1. 6

    ByAltText · ByTitle

    images (alt) and title attributes

last resort

  1. 7

    ByTestId

    data-testid="…" when nothing above works

Query the page the way a user (or a screen reader) finds things. If ByRole can't find your button, a real user with a screen reader may not either.

getByRole covers most cases. The name option is the element's accessible name: for a button or link, its text; for an input, its label; for an image, its alt.

screen.getByRole("button", { name: "Search" });
screen.getByRole("link", { name: /cart/i });  // a regex: case-insensitive, partial
screen.getByRole("heading", { level: 3 });
screen.getByRole("textbox", { name: "Search dishes" }); // an <input> with that label

Use data-testid only when nothing else works, like a chart drawn on a canvas: <div data-testid="price-chart"> and screen.getByTestId("price-chart").

getBy, queryBy, findBy

Each query comes in six variants. Pick by what you expect to happen:

Variant0 matches1 match2+ matchesUse it when
getBy…throwselementthrowsThe element should be there now
queryBy…nullelementthrowsYou're checking it's not there
findBy…rejectselement (promise)rejectsIt appears later (after a fetch). await it.
getAllBy…throwsarrayarraySeveral should be there
queryAllBy…[]arrayarraySeveral, or none
findAllBy…rejectsarray (promise)array (promise)Several, later

findBy retries until the element shows up or 1000 ms pass. More on async in the last topic.

jest-dom matchers

MatcherChecks
toBeInTheDocument()It's on the page
toHaveTextContent("₹120")Its text includes this
toBeVisible()Not hidden by CSS or hidden
toBeDisabled() / toBeEnabled()Button or input state
toHaveValue("burger")An input's current value
toHaveAttribute("href", "/cart")An attribute's value
toBeChecked()A checkbox or radio is ticked
toHaveClass("active")Has a class (use sparingly: users don't see class names)

Gotchas

Recall

Can you answer these?

0/4

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.