开玩笑+打字稿+绝对路径(baseUrl)给出错误:找不到模块 [英] Jest + Typescript + Absolute paths (baseUrl) gives error: Cannot find module
问题描述
我正在设置配置以在create-react-app +打字稿应用程序(我从中弹出)中运行测试.我正在使用笑话+酶.我在tsconfig.json中设置了baseUrl='./src'
,以便在导入模块时可以使用绝对路径.例如,这是我的一个文件中的典型import语句:
I am setting a configuration to run my tests in a create-react-app + typescript app (from which I have ejected). I am using jest + enzyme. In my tsconfig.json I have set baseUrl='./src'
so I can use absolute paths when I import modules. For example this is a typical import statement in one of my files:
import LayoutFlexBoxItem from 'framework/components/ui/LayoutFlexBoxItem';
您可以看到该路径是绝对路径(来自/src文件夹),而不是相对路径.
当我在调试模式(yarn start
)
You can see that the path is absolute (from /src folder) and not relative.
This works fine when I run in debug mode ( yarn start
)
但是当我运行测试(yarn test
)时,出现此错误:
But when I run my test ( yarn test
), I get this error:
Cannot find module 'framework/components/Navigation' from 'index.tsx'
因此,尽管我在tsconfig.json中进行了设置,但看起来jest无法解析此绝对路径.这是我的tsconfig.json:
So it looks like jest is not able to resolve this absolute path although I have set it up in my tsconfig.json. This is my 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"
]
}
现在,我可以看到在项目的根目录下有一个生成的tsconfig.test.json
.这是用于测试的ts配置.这是它的内容:
Now I can see that there is a generated tsconfig.test.json
at the root of my project. This is the ts configuration used for test. And here is its content:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs"
}
}
如您所见,此处的模块"为commonjs
,而在默认配置中为esnext
.这可能是原因之一吗?
As you can see the "module" is commonjs
here whereas in the default configuration it is esnext
. Could this be one reason?
有人能用Jest和绝对路径对他的打字稿项目进行单元测试吗?还是这是一个已知的错误?由于我已退出默认配置,因此我的webpack配置中是否有一些设置可以设置?
Has any one been able to unit test his typescript project with Jest and absolute path? or is this a known bug? Since I have ejected from default configuration, are there some settings to put in my webpack configuration?
感谢您的输入和建议.
推荐答案
我在同样的问题上苦苦挣扎,实际上,事实证明,简单的更改似乎可以解决问题.
I was struggling with the same problem and actually it turns out that a simple change seems to do the trick.
我刚刚更新了jest.config.js
之前
moduleDirectories: ['node_modules']
之后
moduleDirectories: ['node_modules', 'src']
希望有帮助,
安托万
Hope it helps,
Antoine
这篇关于开玩笑+打字稿+绝对路径(baseUrl)给出错误:找不到模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!