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


expect(screen.getByText('User does not exist.')).toBeInTheDocument()

I'm writing the unit test for my web app, I use toBeInTheDocument() in my code, but after i run npm test in terminal, it shows that 'Cannot find module '@testing-library/jest-dom/extend-expect' from 'jest.setup.js''.

I have a jest.setup.js file which includes the code:require('@testing-library/jest-dom/extend-expect');

and also a jest.config.js file which includes the code: setupFilesAfterEnv:["./jest.setup.js"],

and I also import '@testing-library/jest-dom/extend-expect'; in my test.tsx file, also check the node_modules there is @testing-library/jest-dom under it. what should I do now?`

5 Answers 5

110

This was a breaking change in version 6.0 that removed the extend-expect entry point in favor of a default entry point and some platform specific ones. For my use case, the default entry point worked:

import '@testing-library/jest-dom'
Sign up to request clarification or add additional context in comments.

Comments

30

Remove extend-expect from your import:

import '@testing-library/jest-dom'

Comments

11

Changing setupFilesAfterEnv: ["@testing-library/jest-dom/extend-expect"] to setupFilesAfterEnv: ["@testing-library/jest-dom"] in jest.config.js file worked fine.

Update:

If you use jest setup file do following

  • add import "@testing-library/jest-dom" inside jest.setup.js.
  • add reference to setup file in jest.config.js:
    setupFilesAfterEnv: ["<rootDir>/jest.setup.js"]
    

Comments

3

I also encountered the same problem, and the issue was with the @testing-library/jest-dom version 6.1.4, which I changed to version 5.16.5

1 Comment

shouldn't have downgraded, there are security vulnerabilities in 5.16.5 - the answer is pretty clear above in saying you need to update your import to only be import '@testing-library/jest-dom'
0

This issue can also occur if you use a path alias like "@*": ["./*"], in your tsconfig.json or jest.config.ts. When using wildcard path aliases, Jest may fail to resolve modules correctly because it doesn't know how to map the alias to the actual file paths.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.