Jest-如何在babel-jest中使用根斜杠导入?

dag*_*oin 5 jestjs babeljs babel-jest es6-modules

我正在使用Babel Jest转换我的代码以进行测试。我不知道如何使用相对于项目根目录的路径。

例如,如果我在测试文件中导入以下模块:/imports/ui/myModuleJest抛出错误

Cannot find module 
'/Users/me/dev/myProject/Users/me/dev/myProject/imports/ui/myModule' from 'test.jsx'`
Run Code Online (Sandbox Code Playgroud)

但是,如果我导入一个具有相对路径的模块,例如:../../ui/myModule它起作用。

我的.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"
      ]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我的笑话配置是:

  "jest": {
    "roots": ["<rootDir>/imports/tests/jest"]
  },
Run Code Online (Sandbox Code Playgroud)

Ily*_*Zub 1

例如,您可以使用moduleNameMapper配置选项。

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

// test.jsx
import myModule from 'imports/ui/myModule';
Run Code Online (Sandbox Code Playgroud)

SO 的相关答案:Testing with Jest and Webpack aliases

jest官方文档中的另一个示例: https://facebook.github.io/jest/docs/en/webpack.html#configuring-jest-to-find-our-files