React / 73
render, screen and queries: finding things like a user
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
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
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'sdocument.body.screenqueries the whole document. Prefer it over the valuesrenderreturns: one import, and it always looks at the current page.- Queries like
getByRolereturn a real DOM element. jest-dom matchers liketoBeInTheDocument()check it.
Which query? Ask what the user sees
accessible to everyone · use these first
- 1
ByRole
buttons, links, headings, inputs: getByRole("button", { name: "Add" })
- 2
ByLabelText
form fields with a <label>
- 3
ByPlaceholderText
only if there's no label
- 4
ByText
paragraphs, spans, divs (non-interactive text)
- 5
ByDisplayValue
the current value of a filled-in input
semantic
- 6
ByAltText · ByTitle
images (alt) and title attributes
last resort
- 7
ByTestId
data-testid="…" when nothing above works
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 labelUse 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:
| Variant | 0 matches | 1 match | 2+ matches | Use it when |
|---|---|---|---|---|
getBy… | throws | element | throws | The element should be there now |
queryBy… | null | element | throws | You're checking it's not there |
findBy… | rejects | element (promise) | rejects | It appears later (after a fetch). await it. |
getAllBy… | throws | array | array | Several should be there |
queryAllBy… | [] | array | array | Several, or none |
findAllBy… | rejects | array (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
| Matcher | Checks |
|---|---|
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.
