React-testing-library why is toBeInTheDocument() not a function
Upon seeing toBeInTheDocument()
is not a function error, it's likely that jest-dom matchers aren't set up. Correct this by:
-
Installing
@testing-library/jest-dom
: -
Importing it in your test file:
-
Or assuring it's globally loaded in your Jest config:
After these steps, toBeInTheDocument()
will be rightfully accepted by Jest as a valid matcher.
Global setup of jest-dom
You can avoid importing jest-dom in every test file by setting a Jest configuration or a setupTest.js file once. Here's how:
-
In your root project directory, create a
jest.config.js
: -
Create a
jest.setup.js
file also in the base directory:
With this approach, you have a cleaner codebase, and the additional matchers are available in every test file.
Power up with additional matchers
The @testing-library/jest-dom
adds a host of custom matchers to Jest, giving your assertions more expression. Some key matchers are:
- toHaveClass — Validates if an element has specific classes.
- toBeVisible — Checks if an element is visible to the user.
- toHaveAttribute — Checks an element's attribute and its value.
These matchers make your test more descriptive and provide better error understanding.
TypeScript setup
When using TypeScript, you might need additional configurations:
-
Install type definitions:
-
Set
preset
to'ts-jest'
in jest.config.js to include TypeScript files. -
Include your Jest setup file paths in the
include
array of your TypeScript configuration.
With these in place, TypeScript provides better development experience with auto-suggestions and type checking for matchers.
Beware of common pitfalls
Several issues might keep toBeInTheDocument()
unrecognized. Typical ones include:
- Incorrect path in your
setupFilesAfterEnv
configuration. - Not restarting your test runner after adding new configurations or packages.
- Forgotten
import
statement if you're not using Jest setup files method.
Remedy these areas if toBeInTheDocument()
isn't being recognized.
Was this article helpful?