12

It does not appear to respect the NODE_PATHS env variable, and instead just looks in the current directory.

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
limscoder
  • 3,037
  • 2
  • 23
  • 37

6 Answers6

9

Ran into the same issue where Jest didn't respect webpack module resolve alias.

In jest.config.js:

moduleNameMapper: {
    'Services(.*)$': '<rootDir>/src/services/$1'
}

You can now use the following import statement:

import { validateEmail } from 'Services/utilities';
ivcubr
  • 1,988
  • 9
  • 20
  • 28
Rami
  • 103
  • 1
  • 5
8

From Jest doc:

https://jestjs.io/docs/en/configuration

in package.json define:

"jest": {
  "modulePaths": [
    "<rootDir>/src/"
  ],
},
7

Jest does not read NODE_PATH. In our project where we use webpack we faced problems with alias and moduleDirectories. Jest didn't resolve paths correctly. So we solved that like this: Suppose you want to import

import SomeComp from 'components/SomeComp';

which is located in /src/components/SomeComp/index.js

In package.json define:

"jest": {
  "moduleNameMapper": {
    "/src/(.*)": "<rootDir>/src/$1"
  }
},
kurumkan
  • 2,635
  • 3
  • 31
  • 55
  • not working for me, https://stackoverflow.com/questions/67633346/set-absolute-path-for-jest-in-react-project – Niki May 21 '21 at 08:45
2

At the moment Jest doesn't support NODE_PATH in its module resolution code (for no reason other than the fact that it just wasn't ever built).

We're tracking the issue here for now: https://github.com/facebook/jest/issues/102

1

Had the same problem, here's how I fixed it. Let's say you are trying to import src/components/404.vue in your package.json:

... 
  "jest": {
    "modulePaths": [
      "<rootDir>/src/components"
    ]
  }
...

the absolute path '/src/components/' can now be resolved in your 404.test.js as:

import Page404 from '404.vue'
Fi Li Ppo
  • 107
  • 11
0

just put this inside your package.json

"jest": {
  "modulePaths": [
    "<rootDir>"
  ],
},