【发布时间】:2021-11-17 23:29:06
【问题描述】:
我最近创建了一个别名路径来导入我的组件,这样我就可以避免导入像 ../../../../componentFolder 这样的组件,而是使用 @src/componentFolder。
我的问题是我的单元测试停止工作,因为它没有找到导入组件的路径。
下面是我的文件结构。
webpack.config.js
tsconfig.json
client
├── jest.config.js
| tsconfig.json
├── src
│ ├── AgentsView
│ | ├── AgentsView.tsx
│ ├── OtherComponent
│ | ├── OtherComponent.tsx
├── test
│ ├── AgentsView
│ | ├── AgentsView.spec.tsx
│ ├── OtherComponent
│ | ├── OtherComponent.spec.tsx
│ ├── tsconfig.json
我的webpack.config.js是这样的
module.exports = {
resolve: {
extensions: ['.mjs', '.js', '.ts', '.tsx', '.scss'],
alias: {
'@src': path.resolve(__dirname, './client/src/'),
'@components': path.resolve(__dirname, './client/src/components/'),
}
}, ...etc
还有我的tsconfig.json 我添加了 2 个paths。
"compilerOptions": {
"jsx": "react",
"sourceMap": true,
"moduleResolution": "node",
"baseUrl": "client",
"paths": {
"@src/*": ["./src/*"],
"@components/": ["./src/components/*"]
},
},
"exclude": ["node_modules", "build"]
所以,我尝试如下更新我的./client/jest.config.js:
module.exports = {
transform: {
'^.+\\.tsx?$': 'ts-jest'
},
globals: {
'ts-jest': {
tsconfig: './client/test/tsconfig.json',
diagnostics: {
ignoreCodes: [151001]
}
}
},
setupFilesAfterEnv: ['./test/toolkit/Setup.js', 'jest-canvas-mock'],
testRegex: '/test/.*spec\\.(jsx?|tsx?)$',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
reporters: ['default', 'jest-junit'],
collectCoverage: true,
coverageDirectory: '../target/coverage/client',
coverageReporters: ['lcov'],
restoreMocks: true,
moduleNameMapper: {
'^@src(.*)': './src',
'^@components(.*)': './src/components',
}
};
我的client/test/tsconfig.json 是
"compilerOptions": {
"moduleResolution": "node",
"baseUrl": "../",
"paths": {
"~/*": ["./*"],
"@src/*": ["./src/*"],
"@components/": ["./src/components/*"]
}
},
但是当我运行测试时我仍然得到错误。我不确定我在这里缺少的确切位置,因为这种包含多个 tsconfig 文件的结构可能会令人困惑。
【问题讨论】:
标签: javascript reactjs webpack jestjs ts-jest