Explain Codes LogoExplain Codes Logo

React-testing-library why is toBeInTheDocument() not a function

javascript
jest
testing-library
best-practices
Nikita BarsukovbyNikita Barsukov·Mar 4, 2025
TLDR

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:

    npm i -D @testing-library/jest-dom
  • Importing it in your test file:

    import '@testing-library/jest-dom';
  • Or assuring it's globally loaded in your Jest config:

    "jest": { "setupFilesAfterEnv": ["@testing-library/jest-dom/extend-expect"] }

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:

    module.exports = { setupFilesAfterEnv: ['<rootDir>/jest.setup.js'], };
  • Create a jest.setup.js file also in the base directory:

    import '@testing-library/jest-dom/extend-expect'; // Look mum, no more importing in every test file!

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:

    npm i -D @types/testing-library__jest-dom
  • 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.