182

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.

Akber Iqbal
  • 14,487
  • 12
  • 48
  • 70
dorriz
  • 1,927
  • 3
  • 12
  • 19
  • I've posted a detailed answer for those who struggle using `ts-jest` without `babel-jest` and nothing works. I hope it will help: https://stackoverflow.com/a/66708479/2170368 – Greg Wozniak Mar 19 '21 at 12:48

16 Answers16

353

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'
Rubens Mariuzzo
  • 28,358
  • 27
  • 121
  • 148
Gio Polvara
  • 23,416
  • 10
  • 66
  • 62
  • 39
    how do you import it, you could have provided the full answer here... – EugenSunic Jan 30 '20 at 23:40
  • 37
    @EugenSunic Simply use `import '@testing-library/jest-dom'` – Cog Jul 24 '20 at 00:01
  • @Cog , is it always like that? – Welp Mar 04 '21 at 11:09
  • 8
    In Create React App `import '@testing-library/jest-dom'` will be in setupTests.ts. When upgrading from an older Create React App you need to create setupTests.ts. See https://github.com/facebook/create-react-app/blob/master/packages/cra-template-typescript/template/src/setupTests.ts – André Ricardo Apr 27 '21 at 10:05
  • 1
    To clarify, it is not only in jest-dom. Other supporting libraries such as Jasmine support it too. – TimewiseGamgee Jul 28 '22 at 15:49
  • If you have `tsconfig.json` you can try to add next: `"types": ["@testing-library/jest-dom"]`, – Vlad Rose Feb 21 '23 at 07:47
152

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"
  ]

Gabriel Graves
  • 1,751
  • 1
  • 22
  • 40
Jafin
  • 4,153
  • 1
  • 40
  • 52
13

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';
ggorlen
  • 44,755
  • 7
  • 76
  • 106
Akber Iqbal
  • 14,487
  • 12
  • 48
  • 70
10

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.

Zargold
  • 1,892
  • 18
  • 24
  • 1
    adding it beneath /src/ when using typescript is a very important hint. I moved my setupTests.ts file due to some refactorings, which broke all tests then – EimerReis Feb 11 '22 at 15:49
  • This worked well, was the best explained answer with clear instructions. Thanks! – hasin Aug 28 '23 at 14:02
10

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 :)

FireFly
  • 121
  • 1
  • 3
7

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 :)

Jesper
  • 670
  • 9
  • 16
5

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.
Thomas Soos
  • 150
  • 2
  • 11
  • This worked for me, thanks! There must be a way to change setupTests.js because probably some configuration key just defaults to this value. – Akos K Jan 13 '23 at 06:35
4
  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: ['<rootDir>/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.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Esmaeil MIRZAEE
  • 1,110
  • 11
  • 14
  • 1
    Thanks! But why would anyone want to use typescript? – Victor Pudeyev Feb 09 '22 at 00:04
  • 1
    Mr. Pudeyev, with respect, I believe that `JavaScript` is designed to perform how it is currently functioning, and TypeScript is developed to avoid quirky edges of JavaScript. We don't know JavaScript; we pretend we know---Getify. You should have deep knowledge of JavaScript to prevent them, so I personally use `TypeScript` to walk on the safety zone. – Esmaeil MIRZAEE Feb 11 '22 at 07:21
3

For anyone out there that like is trying to run tests in Typescript with jest and is still getting the same error even after installing @testing-library/jest-dom and following all the other answers: you probably need to install the type definitions for jest-dom (here) with:

npm i @types/testing-library__jest-dom

or

yarn add @types/testing-library__jest-dom

You need to install them as real dependencies and not as devDependency.

Bolza
  • 1,904
  • 2
  • 17
  • 42
2

the problem already was solved, but i will comment a little tip here, you don't need to create a single file called setup just for this, you just need to specify the module of the jest-dom on the setupFilesAfterEnv option in your jest configuration file.

Like this:

setupFilesAfterEnv: ['@testing-library/jest-dom/extend-expect'],
1

I was having this issue but for @testing-library/jasmine-dom rather than @testing-library/jest-dom.

The process of setup is just a tiny bit different with jasmine. You need to set up the environment in a before function in order for the matchers to be added. I think jest-dom will go ahead and add the matchers when you first import but Jasmine does not.

import { render, screen } from '@testing-library/react';
import MyComponent from './myComponent';
import JasmineDOM from '@testing-library/jasmine-dom';

describe("My Suite", function () {

  beforeAll(() => {
    jasmine.getEnv().addMatchers(JasmineDOM);
  })


  it('render my stuff', () => {
    const { getByText } = render(<MyComponent />);
    const ele = screen.getByText(/something/i);
    expect(ele).toBeInTheDocument();
  });
});
Cameron
  • 2,805
  • 3
  • 31
  • 45
1

If you are using react-script then follow the below steps

  1. Install @testing-library/jest-dom library if not done already using npm i @testing-library/jest-dom.
  2. Put import "@testing-library/jest-dom/extend-expect" in setUpTest.js

If you are using jest then import the library in jest.setup.js file.

Himanshu
  • 71
  • 3
0

If you're using TS You could also add a test.d.ts file to your test directory and use a triple slash directive: ///<reference types='@testing-library/jest-dom'>

0

I didn't have to use @testing-library/jest-dom/extend-expect, just make sure you're on the latest version and it should already be imported as part of @testing-library/jest-dom when using the jest.setup.js file.

CWSites
  • 1,428
  • 1
  • 19
  • 34
0

I fixed this by adding "./jest.setup.js" in the "include" array in tsconfig.json:

"include": ["next-env.d.ts", "/*.ts", "/.tsx", ".next/types/**/.ts", "./jest.setup.js"],

-5

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.

Jane
  • 81
  • 2
  • 9