nx: [jest-dom] TypeError: expect(...).toBeInTheDocument is not a function
Current Behavior
I have configured jest.config.js globally and added setupFilesAfterEnv as explained in https://github.com/testing-library/jest-dom
But setupFilesAfterEnv is not injecting jest.setup.ts file to tests. Thus, compiler cannot find matcher functions of jest-dom.
Note: If I configure it on app/lib level, it’s working. But global configuration is not working
Expected Behavior
import "testing-library/jest-dom"
should be injected to every test file.
Steps to Reproduce
- Create jest.setup.ts file in nx workspace root and import ‘@testing-library/jest-dom’.
- Add
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts']
to global jest.config.js - Use any jest-dom matcher in your test (Example: toBeInTheDocument).
- Run that test.
Failure Logs
Environment
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Reactions: 3
- Comments: 17 (4 by maintainers)
install devDepedencies
@types/testing-library__jest-dom
and add configuration atjest.config.js
Install:
Setting up
setupTests.ts
in root your project and add the following code**/apps/your-app-here/jest.config.ts
with following the codeFrom here you can run the Test smoothly… BUT you still have kind issue with typescript, to fix this follow next step
**/apps/your-app-here/tsconfig.json
You should ready to Go.
FWIW, I recently experienced this error in a non-nx project and resolved it by adding
@types/testing-library__jest-dom
to devDependencies.@jonybekov placing it into the jest.preset.js works oddly enough, only issue you have is the
<rootDir>
is going to be where the project is. so you just have to resolve it like soSee this commit for all that I changed to get it working
though I’ll note I wouldn’t recommend setting this up globally as it will apply to everything in your monorepo, I’d rather suggest setting up a shared jest preset that you import and spread in your projects you wish to use it in. (that is unless your entire monorepo is going to use this library and won’t have conflicts with it)
Any new/tips/tricks how we can use
@testing-library/jest-dom
globally?For me it was enough to add: import ‘@testing-library/jest-dom’ to my setupTest.ts file
@rizaldirnm thanks bro!
@rizaldirnm you should probably put this in the tsconfig.spec.json, not the tsconfig.json.
I’ve tried that But this method requires to have jest.setup.ts file (which imports @testing-library/jest-dom) in every nx project (apps, libs and etc.) where we need jest-dom
The method I want is to setup jest-dom only once, in the root of nx workspace