我有一个全新的 NestJS 应用程序。我正在尝试运行单元测试,但在使用绝对路径(“src/users/...”)时,由于“找不到模块..”,它们一直失败,但在使用相对路径(“./users/..”)。我这里的配置有什么问题吗?
package.json 中的 Jest 设置:
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
tsconfig.json:{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true
}
}
最佳答案
我有同样的问题,问题是 Nestjs 创建的默认 Jest 配置。
我改了"rootDir": "src"
至"rootDir": "./"
并添加 "modulePaths": ['<rootDir>']
.
最后,我的 Jest 配置如下所示:
moduleFileExtensions: ['js', 'json', 'ts'],
rootDir: './',
modulePaths: ['<rootDir>'],
testRegex: 'spec.ts$',
transform: {
'^.+\\.(t|j)s$': 'ts-jest'
},
coverageDirectory: './coverage',
testEnvironment: 'node',
如果您的配置有一些相对路径,您可能必须更新它们,因为您的 rootDir
不是 src
了。您甚至可以删除
rootDir
你在 package.json
中设置了 Jest 配置吗?或者如果配置文件位于项目的根目录,如文档中所述:https://jestjs.io/docs/en/configuration#rootdir-string如果你想了解
modulePaths
: https://jestjs.io/docs/en/configuration#modulepaths-arraystring希望它也对你有用。
关于node.js - NestJS Jest 找不到具有绝对路径的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64028100/