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

JavascriptReactjsUnit TestingJestjsReact Testing-Library

Javascript Problem Overview


Here is my code for a tooltip that toggles the CSS property display: block on MouseOver and on Mouse Out display: none.

 it('should show and hide the message using onMouseOver and onMouseOut events respectively', () => {
    const { queryByTestId, queryByText } = render(
      <Tooltip id="test" message="test" />,
    )
    fireEvent.mouseOver(queryByTestId('tooltip'))
    expect(queryByText('test')).toBeInTheDocument()
    fireEvent.mouseOut(queryByTestId('tooltip'))
    expect(queryByText('test')).not.toBeInTheDocument()
    cleanup()
  })

I keep getting the error TypeError: expect(...).toBeInTheDocument is not a function

Has anyone got any ideas why this is happening? My other tests to render and snapshot the component all work as expected. As do the queryByText and queryByTestId.

Javascript Solutions


Solution 1 - Javascript

toBeInTheDocument is not part of RTL. You need to install jest-dom to enable it.

And then import it in your test files by: import '@testing-library/jest-dom'

Solution 2 - Javascript

As mentioned by Giorgio, you need to install jest-dom. Here is what worked for me:

(I was using typescript)

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

Then add an import to your setupTests.ts

import '@testing-library/jest-dom/extend-expect';

Then in your jest.config.js you can load it via:

"setupFilesAfterEnv": [
    "<rootDir>/src/setupTests.ts"
  ]

Solution 3 - Javascript

When you do npm i @testing-library/react make sure there is a setupTests.js file with the following statement in it

> import '@testing-library/jest-dom/extend-expect';

Solution 4 - Javascript

Some of the accepted answers were basically right but some may be slightly outdated: Some references that are good for now:

Here are the full things you need:

  1. in the project's <rootDir> (aka where package.json and jest.config.js are), make sure you have a file called jest.config.js so that Jest can automatically pick it up for configuration. The file is in JS but is structured similarly to a package.json.
  2. Make sure you input the following:
  module.exports = {
    testPathIgnorePatterns: ['<rootDir>/node_modules', '<rootDir>/dist'], // might want?
    moduleNameMapper: {
      '@components(.*)': '<rootDir>/src/components$1' // might want?
    },
    moduleDirectories: ['<rootDir>/node_modules', '<rootDir>/src'],
    setupFilesAfterEnv: ['<rootDir>/src/jest-setup.ts'] // this is the KEY
    // note it should be in the top level of the exported object.
  };
  1. Also, note that if you're using typescript you will need to make sure your jest-setup.ts file is compiled (so add it to src or to the list of items to compile in your tsconfig.json.

  2. At the top of jest-setup.ts/js (or whatever you want to name this entrypoint) file: add import '@testing-library/jest-dom';.

  3. You may also want to make sure it actually runs so put a console.log('hello, world!');. You also have the opportunity to add any global functions you'd like to have available in jest such as (global.fetch = jest.fn()).

  4. Now you actually have to install @testing-library/jest-dom: npm i -D @testing-library/jest-dom in the console.

With those steps you should be ready to use jest-dom:

Without TS: you still need:

  1. npm i -D @testing-library/jest-dom
  2. Creating a jest.config.js and adding to it a minimum of: module.exports = { setupFilesAfterEnv: ['<rootDir>/[path-to-file]/jest-setup.js'] }.
  3. Creating a [path-to-file]/jest-setup.js and adding to it: import '@testing-library/jest-dom';.

The jest-setup file is also a great place to configure tests like creating a special renderWithProvider( function or setting up global window functions.

Solution 5 - Javascript

Having tried all of the advice in this post and it still not working for me, I'd like to offer an alternative solution:

Install jest-dom:

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

Then create a setupTests.js file in the src directory (this bit is important! I had it in the root dir and this did not work...). In here, put:

import '@testing-library/jest-dom'

(or require(...) if that's your preference).

This worked for me :)

Solution 6 - Javascript

I had a hard time solving that problem so I believe it's important to note the followings if you're using CREATE REACT APP for your project:

  1. You DO NOT need a jest.config.js file to solve this, so if you have that you can delete it.
  2. You DO NOT need to change anything in package.json.
  3. You HAVE TO name your jest setup file setupTests.js and have it under the src folder. It WILL NOT work if your setup file is called jest.setup.js or jest-setup.js.

Solution 7 - Javascript

None of the answers worked for me because I made the silly mistake of typing toBeInDocument() instead of toBeInTheDocument(). Maybe someone else did the same mistake :)

Solution 8 - Javascript

  1. install required packages

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

  2. create jest-setup.js in the root folder of your project and add

    import '@testing-library/jest-dom'

  3. in jest.config.js

    setupFilesAfterEnv: ['/jest-setup.js']

  4. TypeScript only, add the following to the tsconfig.json file. Also, change .js extension to .ts.

    "include": ["./jest-setup.ts"]

toBeInTheDocument() and many similar functions are not part of the React-testing-library. It requires installing an additional package.

Solution 9 - Javascript

Instead of doing:

    expect(queryByText('test')).toBeInTheDocument()

you can find and test that it is in the document with just one line by using

    let element = getByText('test');

The test will fail if the element isn't found with the getBy call.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondorrizView Question on Stackoverflow
Solution 1 - JavascriptGiorgio Polvara - GpxView Answer on Stackoverflow
Solution 2 - JavascriptJafinView Answer on Stackoverflow
Solution 3 - JavascriptAkber IqbalView Answer on Stackoverflow
Solution 4 - JavascriptZargoldView Answer on Stackoverflow
Solution 5 - JavascriptFireFlyView Answer on Stackoverflow
Solution 6 - JavascriptThomas SoosView Answer on Stackoverflow
Solution 7 - JavascriptJesperView Answer on Stackoverflow
Solution 8 - JavascriptEsmaeil MIRZAEEView Answer on Stackoverflow
Solution 9 - JavascriptJaneView Answer on Stackoverflow