Getting one element vs multiple elements

So far each lesson has been using functions such as screen.getByText() and our example components had exactly one element on the page that would match that.

You will quickly find situations where more than one element matches your query. In this case, getBy... functions throw an error indicating multiple matches.

This might seem surprising at first, but it is useful: be explicit and use getAllBy.../queryAllBy... when more than one element is expected. This helps surface ambiguous queries early and prevents flaky tests.

// Multiple buttons expected:
const buttons = screen.getAllByRole(
  'button',
  { name: 'Delete' }
);
expect(buttons).toHaveLength(2);

When your queries return multiple results, there are several strategies you can use to handle and test these scenarios effectively.

Read on to find out how to handle multiple matches!

Loading full lesson content & code...

Ready to try running tests for this lesson?