How to use slash import using babel-jest?

I use Babel Jest to translate my code for testing purposes. I cannot figure out how to use the path relative to the root of the project.

For example, if in a test file I import a module using: /imports/ui/myModuleJest gives 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, for example: ../../ui/myModuleit 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 Configuration:

  "jest": {
    "roots": ["<rootDir>/imports/tests/jest"]
  },
+4
source share
1 answer

For example, you can use configurations . moduleNameMapper moduleNameMapper

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

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

SO: Jest Webpack

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

0

Source: https://habr.com/ru/post/1670920/


All Articles