Course contentsShow
← React
Lesson 2058 of 2,39646. Testing React with RTLFree lesson

queryBy vs getBy: Asserting Absence

Using queryBy variants that return null instead of throwing when elements don't exist.

queryBy vs getBy: Asserting Absence

What You'll Learn

You'll learn when to use queryBy queries instead of getBy to test that elements don't exist without causing test failures.

The Core Difference

When you use getBy variants (like getByRole or getByText) and the element isn't found, RTL throws an error and your test fails immediately. This is perfect for asserting that something should be present.

But what if you want to verify something is not rendered? That's where queryBy variants come in.

queryBy returns null when an element doesn't exist instead of throwing an error. This lets you write assertions like expect(element).not.toBeInTheDocument() or expect(element).toBeNull().

When to Use Each

// ✅ Element SHOULD exist - use getBy
const button = screen.getByRole('button', { name: /submit/i });
expect(button).toBeInTheDocument();

// ✅ Element should NOT exist - use queryBy
const errorMessage = screen.queryByText(/error occurred/i);
expect(errorMessage).not.toBeInTheDocument();

// ❌ Wrong - this would throw before you could assert
const errorMessage = screen.getByText(/error occurred/i);
expect(errorMessage).not.toBeInTheDocument(); // Never reached!

The Analogy

Think of getBy as a strict bouncer: "No ID? You're not getting in, and I'm making a scene about it." Meanwhile, queryBy is the polite host: "Not here? No problem, I'll just tell you they're absent."

Use getBy when absence is a failure. Use queryBy when absence is expected and you want to verify it.

Key Takeaway: Use queryBy variants when asserting that elements don't exist; they return null instead of throwing, allowing you to test for absence without failing the test prematurely.