5

I am using Babel Jest to transpile my code for testing purposes. I can't get how to use path relative to the project root.

For example, if in a test file I import a module with: /imports/ui/myModule Jest throws an error

Cannot find module 
'/Users/me/dev/myProject/Users/me/dev/myProject/imports/ui/myModule' from 'test.jsx'`

But if I import a module with a relative path like: ../../ui/myModule it works.

My .babelrc:

{
  "plugins": [
    "transform-decorators-legacy",
    "transform-class-properties",
    "babel-root-slash-import"
  ],
  "presets": [
    "es2015",
    "react",
    "stage-0"
  ],
  "env": {
    "test": {
      "plugins": [
        "transform-decorators-legacy",
        "transform-class-properties",
        "babel-root-slash-import"
      ],
      "presets": [
        "es2015",
        "react",
        "stage-0"
      ]
    }
  }
}

My Jest config is:

  "jest": {
    "roots": ["<rootDir>/imports/tests/jest"]
  },
Vijay Gaikwad
  • 457
  • 1
  • 4
  • 16
dagatsoin
  • 2,626
  • 6
  • 25
  • 54

1 Answers1

1

At instance, you can use moduleNameMapper config option.

// package.json
{
  "jest": {
    "roots": ["<rootDir>/imports/tests/jest"]
  },
  "moduleNameMapper": [
    "^ui/(.*)$": "<rootDir>/imports/ui/$1"
  ]
}

// test.jsx
import myModule from 'imports/ui/myModule';

Related answer on SO: Testing with Jest and Webpack aliases

Another example from the jest's official documentation: https://facebook.github.io/jest/docs/en/webpack.html#configuring-jest-to-find-our-files

ilyazub
  • 1,226
  • 13
  • 23