Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest - How to use root slash import with babel-jest?

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"]
  },
like image 552
dagatsoin Avatar asked Nov 20 '22 03:11

dagatsoin


1 Answers

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

like image 190
Ilya Zub Avatar answered Nov 25 '22 08:11

Ilya Zub