我正在设置一个配置,以在create-react-app + typescript应用程序中运行我的测试(我已经弹出)。 我正在使用jest + enzyme。 在我的tsconfig.json中,我设置了baseUrl='./src'
,因此当我导入模块时,我可以使用绝对路径。 例如,这是我文件中的典型导入语句:
import LayoutFlexBoxItem from 'framework/components/ui/LayoutFlexBoxItem';
您可以看到路径是绝对的(从/src文件夹),而不是相对的。
当我在调试模式下运行时(yarn start
),这很好用。
但是当我运行我的测试(yarn test
)时,我会收到以下错误:
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"
]
}
现在我可以看到项目根目录下生成了一个
tsconfig.test.json
。这是用于测试的ts配置文件。以下是它的内容:{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs"
}
}
正如您所看到的,“module”在此处为commonjs
,而在默认配置中为esnext
。这可能是一个原因吗?
有人能够使用Jest和绝对路径对其TypeScript项目进行单元测试吗?还是这是一个已知的错误?由于我已经从默认配置中退出,是否有一些设置要放在我的webpack配置中?
感谢您的意见和建议。
jest
部分添加了以下内容。 - Zartosht SepidemanmoduleDirectories: ['node_modules', '.']
。请注意不要改变原意,但需要使语言更通俗易懂。 - Maciej Krawczyk.vscode/settings.json
文件中,或在UI中更改设置:"javascript.preferences.importModuleSpecifier": "non-relative"
。 - Archibaldtsconfig
中的baseUrl
是./
,那么这肯定有效。 - Ilya Kushlianski