15

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?

Inovramadani
  • 1,955
  • 3
  • 14
  • 34

2 Answers2

22

Solved with:

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

on src/setupTests.js

Inovramadani
  • 1,955
  • 3
  • 14
  • 34
12

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

user3142695
  • 15,844
  • 47
  • 176
  • 332