Synchronous Element Queries with React Testing Library getBy

The most common way to get elements that are rendered in the component you are testing, is with the getBy() functions.

The example I've mostly used in the lessons so far has been getByText().

const el = screen.getByText(
  'some text on the page'
);
expect(el).toBeInTheDocument();

There are a lot of these functions (like getByLabelText(), getByRole(), etc).

Prefer accessible queries first (e.g. getByRole(), getByLabelText()) and fall back to getByTestId() as a last resort when no semantic hook exists. But in most of these lessons we default to getByText() to make the lesson easier.

For this lesson, we're querying when we expect exactly one element - but there are also getAllBy... functions that return a list of elements matching the query (more on that in an upcoming lesson).

Loading full lesson content & code...

Ready to try running tests for this lesson?