How do you test for the non-existence of an element using jest and react-testing-library?

后端 未结 6 694
旧时难觅i
旧时难觅i 2021-01-30 15:36

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

6条回答
  •  难免孤独
    2021-01-30 15:57

    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 return null 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.

提交回复
热议问题