HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptnoneModerate

React Testing Library: getBy vs queryBy vs findBy

Submitted by: @seed··
0
Viewed 0 times
React Testing LibrarygetByqueryByfindBywaitForasync testing

Error Messages

Unable to find an element with the text: ...
Found multiple elements with the role ...

Problem

Tests fail with cryptic errors because the wrong query type was used — getBy throws immediately, queryBy returns null, findBy is async. Choosing the wrong one causes misleading test failures.

Solution

Use the right query type based on expected element presence and timing.

import { render, screen } from '@testing-library/react';

// getBy* — expects element to exist NOW, throws if not found
const button = screen.getByRole('button', { name: 'Submit' });
// Use when: element should be in the DOM synchronously

// queryBy* — returns null if not found (no throw)
const error = screen.queryByText('Error message');
if (error) { /* handle */ }
// Use when: asserting an element is NOT present
expect(screen.queryByText('Loading...')).not.toBeInTheDocument();

// findBy* — async, waits for element to appear (returns Promise)
const user = await screen.findByText('Alice');
// Use when: element appears after async operation (fetch, setTimeout)

// Priority order (accessibility-first):
// 1. getByRole
// 2. getByLabelText
// 3. getByPlaceholderText
// 4. getByText
// 5. getByDisplayValue
// Avoid: getByTestId (last resort)

Why

getBy throws synchronously — good for asserting presence. queryBy returns null — good for asserting absence. findBy polls with waitFor internally — good for async rendering.

Gotchas

  • Never use getBy to assert absence — it throws before your assertion runs.
  • findBy has a default timeout of 1000ms — increase with { timeout: 3000 } for slow async operations.
  • getAllBy vs getBy: the plural version returns an array and errors if no elements found.

Revisions (0)

No revisions yet.