Q:

Resolve file paths in Jest

I have a React based app in which I have a test file which I intend to run through Jest. The test requires importing classes from other files. The file that I import further imports other files and so on. The project has alias for many paths to lessen the typing when importing them (this is configured in Webpack). 
When I run jest command in npm, I get an error saying 'Cannot find module ...`. How can I resolve file paths when running Jest? I can't mock the modules as these are custom modules which are required to run the test.

A:

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

A:

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

A:

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. 

