问题
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
回答1:
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/helper/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
回答2:
forget the ~
character;
first define root directory to jest (i.e. src/
);
then import your stuff from that root directory; (e.g. import { abc } from 'lib/dates'
)
by the way you can always import your stuff from default root without any configuration like this: import { abc } from 'src/lib/dates'
further read if you are using create-react-app jest absolute import
来源:https://stackoverflow.com/questions/63709973/jest-test-runs-cannot-find-module-error