admin管理员组

文章数量:1128268

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.

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.

Share Improve this question edited Sep 20, 2021 at 21:14 Akber Iqbal 15k12 gold badges53 silver badges75 bronze badges asked Jun 11, 2019 at 15:36 dorrizdorriz 2,6493 gold badges13 silver badges19 bronze badges 1
  • 1 I've posted a detailed answer for those who struggle using ts-jest without babel-jest and nothing works. I hope it will help: stackoverflow.com/a/66708479/2170368 – Greg Wozniak Commented Mar 19, 2021 at 12:48
Add a comment  | 

18 Answers 18

Reset to default 475

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'

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

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';

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

  • https://github.com/testing-library/jest-dom
  • https://jestjs.io/docs/configuration

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.

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

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

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.
  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.

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.

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'],

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();
  });
});

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.

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.

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'>

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

Besides all the answers mentioned in the comments above in my case replacing 'import' with 'require' helped. Even though all other inner files are imported via 'import' and other settings from the comments above were implemented too, they didn't helped until I've changed import

const { expect, describe, it } = require('@jest/globals');

This is what worked for me in TypeScript

Install jest-dom:

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

Add type definition for jest-dom under compilerOptions in tsconfig.json:

{
  "compilerOptions": {
     // ...
     "types": ["@testing-library/jest-dom"],
     // ...
  }
}

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.

本文标签: javascriptreacttestinglibrary why is toBeInTheDocument() not a functionStack Overflow