Optional Element Queries with React Testing Library queryBy

Previous lessons showed how to find and check that elements are rendered.

But what about when an item should NOT be there?

That is what queryBy... is for.

Out of the getBy..., queryBy... and findBy..., only the queryBy... functions return null when nothing is found, but they still throw if more than one element matches.

(The others - getBy... and findBy... - throw when nothing or multiple elements match.)

Typical use is like this:

const maybeThere = screen.queryByText(
  'not in the dom'
);

expect(maybeThere).toBeNull();

Loading full lesson content & code...

Ready to try running tests for this lesson?