Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Part 14 / Topic 1 of 7

Query priority - and why getByRole comes first

Testing Library ranks queries by how close they get to what a real user - sighted, using a screen reader, or navigating by keyboard - actually perceives, not by what is convenient to select in a component's markup. examples/01_query_priorities.jsx's OrderCard is reachable several different ways on purpose:

// examples/01_query_priorities.jsx
<article className="order-card" data-testid="order-card">
  <h3>Order {orderId}</h3>
  <p>Status: <span className="status-badge">{status}</span></p>
  <label>Delivery notes
    <input type="text" placeholder="e.g. leave at the gate" />
  </label>
  <button onClick={() => setExpanded((e) => !e)}>{expanded ? "Hide details" : "Show details"}</button>
  ...
</article>

examples/01_query_priorities.test.jsx queries it in the order Testing Library's own docs recommend: getByRole("heading", { name: "Order SW-7742" }) and getByRole("button", { name: "Show details" }) first (every interactive or structural element already has a role and an accessible name - nothing extra to add), getByLabelText("Delivery notes") for the form field (reads the real <label>, the same way a sighted user does), getByPlaceholderText only as a fallback for a field with no real label, getByText for plain visible text with no interactive role, and getByTestId("order-card") last, kept to prove it works at all - not because the test needed it. Every one of this part's claims above was already provable without that test id, with no change to the component.

This repo's own existing tests already lean on getByRole constantly - stage-2-intermediate/part-09-usecontext/examples/02_create_context_provider_consumer.test.jsx finds its toggle button with getByRole("button", { name: ... }), and every fetch test in stage-3-advanced/part-11-fetching-data/ finds loading/error/success text the same role-or-text-first way. This part just names the rule those files were already following.

Done here? The practice set for Part 14 — including the solutions — is on the part page.

Search the guide