Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 17.3 — Rendering and Querying
React · Example 2 of 3

getBy, queryBy and findBy

The status appears after 300 ms. getBy and queryBy look once, right now, so they miss it. findBy waits and finds it.

render() mounts a component into the test page and screen finds elements the way people do: by role and accessible name first, then label, text and the rest, with getBy, queryBy and findBy for present, absent and not-yet-there elements.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write queries for: a search field labelled "Search products", a level-1 heading "Shop", and an image with alt "Cart". Use the best query for each.

02

A list shows three products, each with an "Add to cart" button. Write a test (live helper style) that clicks the button for "Mango" only.

Explain it without notes

01

Why does Testing Library recommend getByRole first? What is the full priority?

02

Explain getBy, queryBy and findBy and when to use each.

03

What does within do? Give an example where you need it.

04

A getByRole call fails although you can see the button in the browser. How do you debug it?

getBy, queryBy and findBy

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

getBy   → TestingLibraryElementError: Unable to find an accessible element with the role "status"
queryBy → null
findBy  → Saved!
getAllByText(/Sav/)     → 1
queryAllByText(/oops/)  → []