我正在设置一个配置,以便在create-react-app + typescript应用程序中运行我的测试(
我从那里弹了出来
)。我正在使用jest +酶。在我的tsconfig.json中,我设置了
因此,我可以在导入模块时使用绝对路径。例如,在我的一个文件中,这是一个典型的import语句:
import LayoutFlexBoxItem from 'framework/components/ui/LayoutFlexBoxItem';
您可以看到该路径是绝对路径(来自/src文件夹),而不是相对路径。当我在调试模式下运行时,它工作得很好(
)
但是当我运行我的测试时(
),我得到这个错误:
Cannot find module 'framework/components/Navigation' from 'index.tsx'
所以看起来jest不能解决这个绝对路径,尽管我已经在我的tsconfig.json中设置了它。这是我的tsconfig.json:
{
"compilerOptions": {
"outDir": "dist",
"module": "esnext",
"target": "es5",
"lib": ["es6", "dom"],
"sourceMap": true,
"allowJs": true,
"jsx": "react",
"moduleResolution": "node",
"rootDir": "src",
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": true,
"baseUrl": "./src"
},
"exclude": [
"node_modules",
"build",
"dist",
"config",
"scripts",
"acceptance-tests",
"webpack",
"jest",
"src/setupTests.ts"
]
}
现在我可以看到有一个生成的
在我项目的根部。这是用于测试的ts配置。下面是它的内容:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs"
}
}
正如您所看到的,"module“是
在这里,而在默认配置中,它是
..。这可能是一个原因吗?
有没有人能够用Jest和absolute path对他的typescript项目进行单元测试?或者这是一个已知的bug?由于我已经从默认配置中弹出,是否有一些设置可以放入我的webpack配置中?
感谢您的意见和建议。
发布于 2018-07-04 21:30:28
我也在为同样的问题而苦苦挣扎,事实证明,一个简单的改变似乎就能做到这一点。
我刚刚更新了
字段位于
..。
之前
moduleDirectories: ['node_modules']
之后
moduleDirectories: ['node_modules', 'src']
希望能有所帮助。
发布于 2019-06-27 22:09:27
正如在座的许多人所指出的那样
在
需要定义在
..。例如,如果您在
定义如下
// tsconfig.json
{
...
"baseUrl": "src",
"paths": {
"@alias/*": [ 'path/to/alias/*' ]
}
...
}
然后你的
需要在
格式如下:
// jest.config.js
module.exports = {
'roots': [
'/src'
],
'transform': {
'^.+\\.tsx?$': 'ts-jest'
},
'moduleNameMapper': {
'@alias/(.*)': '/src/path/to/alias/$1'
}
};
有了这些,我们就可以提高我们的
转换在中定义的路径的步骤
自动。这是一个
Gist代码片段
为此:
// jest.config.js
function makeModuleNameMapper(srcPath, tsconfigPath) {
// Get paths from tsconfig
const {paths} = require(tsconfigPath).compilerOptions;
const aliases = {};
// Iterate over paths and convert them into moduleNameMapper format
Object.keys(paths).forEach((item) => {
const key = item.replace('/*', '/(.*)');
const path = paths[item][0].replace('/*', '/$1');
aliases[key] = srcPath + '/' + path;
});
return aliases;
}
const TS_CONFIG_PATH = './tsconfig.json';
const SRC_PATH = '/src';
module.exports = {
'roots': [
SRC_PATH
],
'transform': {
'^.+\\.tsx?$': 'ts-jest'
},
'moduleNameMapper': makeModuleNameMapper(SRC_PATH, TS_CONFIG_PATH)
};
发布于 2018-07-30 16:47:41
这是我如何让moduleNameMapper工作的。
在我的tsconfig中使用以下配置:
"paths": {
"@App/*": [
"src/*"
],
"@Shared/*": [
"src/Shared/*"
]
},
下面是moduleNameMapper:
"moduleNameMapper": {
"@App/(.*)": "/src/$1",
"@Shared/(.*)": "/src/Shared/$1"
}
https://stackoverflow.com/questions/50171412
复制相似问题