I have a component library that I\'m writing unit tests for using Jest and react-testing-library. Based on certain props or events I want to verify that certain elements aren\'t
Use queryBy
/ queryAllBy
.
As you say, getBy*
and getAllBy*
throw an error if nothing is found.
However, the equivalent methods queryBy*
and queryAllBy*
instead return null
or []
:
queryBy
queryBy*
queries return the first matching node for a query, and returnnull
if no elements match. This is useful for asserting an element that is not present. This throws if more than one match is found (use queryAllBy instead).queryAllBy
queryAllBy*
queries return an array of all matching nodes for a query, and return an empty array ([]
) if no elements match.
https://testing-library.com/docs/dom-testing-library/api-queries#queryby
So for the specific two you mentioned, you'd instead use queryByText
and queryByTestId
, but these work for all queries, not just those two.