我一直在我的react项目(typescript)中使用jest进行单元测试。现在我已经在webpack和tsconfig中启用了路径别名。为了在jest中使用路径别名,我遵循了这个tutorial。但是当我运行我的测试时,我得到了这个错误:

以下是我的webpack启用路径别名的配置:
alias: {
'ui': path.resolve(__dirname, 'src/framework/components/ui')
}下面是启用路径别名(package.json)的jest配置
"moduleNameMapper": {
"ui": "<rootDir>/src/framework/components/ui/"
}我也尝试了教程中的这个版本:
"moduleNameMapper": {
"^ui/(.*)$1": "<rootDir>/src/framework/components/ui/$1"
}最后是我的tsconfig.json配置:
"baseUrl": "src",
"paths": {
"ui": ["framework/components/ui"]
}当我运行我的测试时,jest实际上解析了路径别名。但它无法拾取作为默认组件公开的组件。例如,这一行:
import Button from './FormComponents/Button';失败,因为“Button”是作为默认值从其模块导出的。
我希望我的问题是有意义的。提前感谢您的帮助。
发布于 2020-12-08 04:33:44
使用ts-jest https://huafu.github.io/ts-jest/user/config/#jest-config-with-helper
// jest.config.js
const { pathsToModuleNameMapper } = require('ts-jest/utils');
// In the following statement, replace `./tsconfig` with the path to your `tsconfig` file
// which contains the path mapping (ie the `compilerOptions.paths` option):
const { compilerOptions } = require('./tsconfig');
module.exports = {
// [...]
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths /*, { prefix: '<rootDir>/' } */ )
};https://stackoverflow.com/questions/51080947
复制相似问题