Resolve file paths in Jest

Jest can handle this with moduleNameMapper
You can define the same aliases you have in webpack here too. This should make jest be able to resolve them.

From the documentation:

And finally we just have the webpack alias left to handle. For that we can make use of the moduleNameMapper option again.

// package.json
{
  "jest": {
    "modulePaths": ["/shared/vendor/modules"],
    "moduleFileExtensions": ["js", "jsx"],
    "moduleDirectories": ["node_modules", "bower_components", "shared"],

    "moduleNameMapper": {
      "^react(.*)$": "<rootDir>/vendor/react-master$1",
      "^config$": "<rootDir>/configs/app-config.js",

      "\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js",
      "\\.(gif|ttf|eot|svg)$": "<rootDir>/__mocks__/fileMock.js"
    }
  }
}

https://facebook.github.io/jest/docs/en/webpack.html#configuring-jest-to-find-our-files


you could as well try to add your aliased folder in moduleDirectories

"moduleDirectories": [
  "src",
  "node_modules"
]

I use this approach when I want to use absolute instead of relative imports like this:

import SomeComponent from 'components/SomeComponent'

note: I have my components folder under /src


You could add 1 line to your Jest config file like this:

module.exports = {
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1"
  }
}

The configuration line above uses regex to map imports starting with the @ character.

Note: (this above configuration code is assuming your source code is located in "project_root/src/"

Then, your import statements in your jest tests will look like this:

import {RepositoryController} from '@/controller/repository'

Which maps to project_root/src/controller/repository. This is much better then the relative path: ../../../src/controller/repository my project would regularly require.


Just a heads up for anyone else running into this: if you followed the Jest getting started documentation, and came across the part that mentions:

Generate a basic configuration file: Based on your project, Jest will ask you a few questions and will create a basic configuration file with a short description for each option

and followed that step, it will generate a jest.config.js file for you.

Subsequent Jest documentation (and SO posts) then refer to putting config options in your package.json, and if you go ahead and put your config changes there, (such as the ones suggested in this thread and others) Jest will ignore it and look at your jest.config.js instead.

(If you're like me) You'll then bang your head against the wall trying to figure out why the config options you've added aren't working even after following them step-by-step, only to later realize that the relatively empty jest.config.js file is squashing everything you've been trying to get to work in package.json which Jest is completely ignoring!

Tags:

Webpack

Jestjs