使用Jest和Webpack别名进行测试

我希望能够在使用笑话时使用webpack别名来解析导入,并且最好参考webpack.aliases以避免重复。

开玩笑的conf:

  "jest": {
    "modulePaths": ["src"],
    "moduleDirectories": ["node_modules"],
    "moduleNameMapper": {
      "^@shared$": "<rootDir>/shared/",
      "^@components$": "<rootDir>/shared/components/"
    }
  },

Webpack别名:

exports.aliases = {
    '@shared': path.resolve(paths.APP_DIR, 'shared'),
    '@components': path.resolve(paths.APP_DIR, 'shared/components'),
};

进口:

import Ordinal from '@shared/utils/Ordinal.jsx';
import Avatar from '@components/common/Avatar.jsx';

由于某种原因,@导致了问题,因此将其删除(使用别名和导入)时,可以找到sharedcomponents仍然无法解决。

 FAIL  src/shared/components/test/Test.spec.jsx
  ● Test suite failed to run

    Cannot find module '@shared/utils/Ordinal.jsx' from 'Test.jsx'

我尝试使用jest-webpack-aliasbabel-plugin-module-resolverJest / Webpack docs

乐LEY2020/03/24 17:23:56

FWIW,尝试切换别名顺序,保持更具体的向上和不具体的向下,例如

"moduleNameMapper": {
  "^@components$": "<rootDir>/shared/components/",
  "^@shared$": "<rootDir>/shared/"
}
古一2020/03/24 17:23:56

由于我在再次阅读之前遇到了相同的问题,因此这次要更仔细地阅读文档。正确的配置应为:

  "jest": {
    "moduleNameMapper": {
      "^@shared(.*)$": "<rootDir>/shared$1",
      "^@components(.*)$": "<rootDir>/shared/components$1"
    }
  },