我一直在使用React在我的React项目(打字稿)中进行单元测试。现在,我在webpack和tsconfig中启用了路径别名。为了通过jest使用路径别名,我遵循了本教程。但是运行测试时出现此错误:
这是我的webpack配置以启用路径别名:
alias: {
'ui': path.resolve(__dirname, 'src/framework/components/ui')
}
Run Code Online (Sandbox Code Playgroud)
这是我开玩笑的配置,以启用路径别名(package.json)
"moduleNameMapper": {
"ui": "<rootDir>/src/framework/components/ui/"
}
Run Code Online (Sandbox Code Playgroud)
我也从教程中尝试了此版本:
"moduleNameMapper": {
"^ui/(.*)$1": "<rootDir>/src/framework/components/ui/$1"
}
Run Code Online (Sandbox Code Playgroud)
最后是我的tsconfig.json配置:
"baseUrl": "src",
"paths": {
"ui": ["framework/components/ui"]
}
Run Code Online (Sandbox Code Playgroud)
当我运行测试时,玩笑实际上会解析路径别名。但是它无法拾取默认情况下暴露的组件。对于此行:
import Button from './FormComponents/Button';
Run Code Online (Sandbox Code Playgroud)
失败,因为“按钮”从其模块默认导出。
我希望我的问题有道理。预先感谢您的帮助。
jez*_*nag 29
尝试
"moduleNameMapper": {
"^ui/(.*)": "<rootDir>/src/framework/components/ui/$1"
}
Run Code Online (Sandbox Code Playgroud)
正则表达式中不应包含 $1,因为 $1 用于替换字符串中以插入捕获的文本。
例如,在您的示例中,“Button”将由 (.*) 捕获,然后用于替换替换字符串中的 $1。
Dan*_*rez 10
使用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>/' } */ )
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
939 次 |
| 最近记录: |