Difference between toBeInTheDocument() and toBeDefined()

Viewed 16

What is the difference between toBeInTheDocument() and toBeDefined() when testing with Jest and React Testing Library? When should they be used?

1 Answers

The @testing-library/jest-dom library provides a set of custom jest matchers that you can use to extend jest. These will make your tests more declarative, clear to read and to maintain.

It solve the below problem:

You want to use jest to write tests that assert various things about the state of a DOM. As part of that goal, you want to avoid all the repetitive patterns that arise in doing so. Checking for an element's attributes, its text content, its css classes, you name it.

From the source code of toBeInTheDocument(), it uses several DOM APIs such as Node.getRootNode() and Node.cloneNode(). You don't need to check if the element is present in the document on your own. This is very convenient and readable.

toBeDefined has nothing to do with DOM API, it's a basic matcher uses const pass = received !== void 0; to check if the value is defined or not.

Related