Got TypeError: expect(...).toBeInTheDocument is not a function even after proper setup

13.6k Views Asked by At

I use Create React App and already declare this on src/setupTests.js:

import '@testing-library/jest-dom';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });

But every time I use expect(anything).toBeInTheDocument() on test file, when running the test I get:

TypeError: expect(...).toBeInTheDocument is not a function

To make sure that the setupTests.js is actually run, I try to use enzyme shallow on test file and it works. So what is the problem with jest-dom actually and how to solve it?

2

There are 2 best solutions below

1
On BEST ANSWER

Solved with:

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

on src/setupTests.js

0
On

It is easier to add in your jest.config.js

module.exports = {
  ...,
  "setupFilesAfterEnv": [
    "<rootDir>/jest.setup.js"
  ]
}

and to create jest.setup.js with the content

import '@testing-library/jest-dom'

With that you don't have to import the jest-dom in every test file