How to Fix "toBeInTheDocument is not a function" Jest Error?

#Why Does This Happen?

This error happens because the toBeInTheDocument() matcher exists in the jest-dom utility library, and is not bundled with jest by default. Therefore, when you use it without installing the jest-dom library it will throw the following error:

// TypeError: expect(...).toBeInTheDocument is not a function
expect(screen.getByText('foobar')).toBeInTheDocument()

#How to Fix the Issue?

To fix this error you need to include jest-dom in your tests. It's a library that extends Jest using custom matchers in order to make assertions on DOM elements easier.

To include jest-dom in all your tests, you can follow these steps:

  1. Install jest-dom Library

    Install jest-dom package:

    npm install --save-dev @testing-library/jest-dom
    

    Or, using yarn:

    yarn add --dev @testing-library/jest-dom
    
  2. Import @testing-library/jest-dom in Tests

    To import jest-dom in all your tests, you need to create a "setupTests.js" file (you can name it however you want) and import "@testing-library/jest-dom" in there, like so:

    // setupTests.js
    import '@testing-library/jest-dom'
    

    Once you've done that, you need to add the setup file in your jest.config.js, like so:

    // jest.config.js
    module.exports = {
      // ...
      setupFilesAfterEnv: ['<rootDir>/setupTests.js'],
      // ...
    }
    
  3. TypeScript Settings

    If you're using TypeScript, then you need to make sure that your setup file has a file extension of ".ts" instead of ".js" to include the necessary types. Additionally, you will need to include your setup file in your tsconfig.json, for example, like so:

    // tsconfig.json
    {
      // ...
      "include": [
        // ...
        "./jest-setup.ts"
      ],
      // ...
    }
    

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.