Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  10] [ 2]  / answers: 1 / hits: 22270  / 4 Years ago, wed, september 2, 2020, 12:00:00

I have been working on a React Typescript repo and have been running into an annoying issue where in jest is not able to resolve imports relative to root dir.


 Cannot find module '~lib/dates' from 'utils.ts'

And this how the import looks like in the component / utils


import { abc } from '~lib/dates';   // this fails to run

If I change this to a relative path jest test runs works as expected


import { abc } from '../../lib/dates';   // this runs as expected

The same path work for some other directories and I am a bit stumped


import { xyz } from '~components/home/constants';   // jest resolves it
import { abc } from '~lib/dates'; // ERR

I tried including moduleNameWrapper in the jestConfig to see if it jest can resolve the imports correctly but it did not help.


package.json


"jest": {
...

"moduleNameWrapper": {
"^~(.*)$": "<rootDir>/src/$1"
}
}

I could for sure update the VS code setting so that auto imports are resolved relatively to the file and not with the root dir but this has been bugging me for a while. It would be great if anyone has any pointers on how best to resolve this.


I am on a monorepo with the following directory structure


repo
server
client
src
components
lib
utils
package.json

More From » typescript

 Answers
39

Your implementation looks right. But it looks like the option moduleNameWrapper was the wrong option, it's supposed to be moduleNameMapper.


I also have an example as same as you which also uses babel as transplier, it works fine as I added moduleNameMapper. Here is the my example:


Jest configuration:


https://github.com/tmhao2005/lerna-demo/blob/master/packages/share/jest.config.js


Here is the file for testing:


https://github.com/tmhao2005/lerna-demo/blob/master/packages/helper/src/index.ts
https://github.com/tmhao2005/lerna-demo/blob/master/packages/helper/src/index.test.ts


[#50672] Saturday, August 22, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kyrona

Total Points: 422
Total Questions: 111
Total Answers: 97

Location: Oman
Member since Wed, Apr 12, 2023
1 Year ago
;