Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *