repost: findByText() vs getByText() vs queryByText()- React Testing Library | by Anjali Ajith | Medium
I have a short-term memory span, so here i am writing blog posts to re-enforce long-term memory. It’s not going to be perfect .
# Cheat Grid
Check if something is on screen right now: getByText()
Check if something will appear later findByText() + await
Check if something is gone / not present queryByText()
# 🔍 Detailed Breakdown
# ✅ 1. getByText
What it does:
Immediately tries to find the element. If not found, it throws an error.
Use When:
The element should already be in the DOM (e.g., static render)
You’re not waiting for state/props/network updates
1 | render(<Greeting />); |
🚫 Don’t use after a button click triggers async logic like fetch .
# ✅ 2. findByText
What it does:
Waits until the element appears in the DOM (max ~1000ms). If still not found, throws an error.
Use When:
- You’re testing async changes
- Something like an API call, a timeout, or animation updates the UI
1 | fireEvent.click(screen.getByText(/submit/i)); |
🚫 Don’t forget the **await** ! It’s a promise.
# ✅ 3. queryByText
What it does:
Tries to find the element right now. If not found, returns **null** instead of throwing.
Use When:
- You want to check if something is not there
- Or that something disappears after an action
1 | // Confirm loading is goneexpect(screen.queryByText(/loading/i)).not.toBeInTheDocument(); |
🚫 Don’t use queryByText to check for something that should be there — it won’t throw if it’s missing, so test might silently pass.
# 💡 Real-World Pattern
1 | fireEvent.click(button); |
# 🧙 Pro Tip:
If you’re ever unsure, ask yourself:
“Is this element already there, will appear*, or* should not be *there?”*
That question always tells you which method to use.