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
2
render(<Greeting />);
expect(screen.getByText(/hello, anju/i)).toBeInTheDocument();

🚫 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
2
3
fireEvent.click(screen.getByText(/submit/i));
const successMsg = await screen.findByText(/submitted successfully/i);
expect(successMsg).toBeInTheDocument();

🚫 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
2
3
4
5
6
7
8
9
10
11
fireEvent.click(button);

// ✅ Shows loading immediately
expect(screen.getByText(/loading/i)).toBeInTheDocument();

// ✅ Shows final message after API completes
const successMsg = await screen.findByText(/success/i);
expect(successMsg).toBeInTheDocument();

// ✅ Loading should now be gone
expect(screen.queryByText(/loading/i)).not.toBeInTheDocument();

# 🧙 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.

Edited on