How to test for the non-existence of an element using Jest and react-testing-library?

Sometimes, we want to test for the non-existence of an element using Jest and react-testing-library.

In this article, we’ll look at how to test for the non-existence of an element using Jest and react-testing-library.

How to test for the non-existence of an element using Jest and react-testing-library?

To test for the non-existence of an element using Jest and react-testing-library, we can use the the not.toBeInTheDocument method.

For instance, we write:

import '@testing-library/jest-dom/extend-expect'
// ...
const submitButton = screen.queryByText('submit')
expect(submitButton).not.toBeInTheDocument()

to call screen.queryByText to select the element by text.

Then we call expect(submitButton).not.toBeInTheDocument to check that the element with text 'submit' isn’t in the document object.

Conclusion

To test for the non-existence of an element using Jest and react-testing-library, we can use the the not.toBeInTheDocument method.