NestJS Jest 找不到具有绝对路径的模块 [英] NestJS Jest cannot find module with absolute path
问题描述
我有一个非常新的 NestJS 应用程序.我正在尝试运行单元测试,但是在使用绝对路径(src/users/...")时由于找不到模块.."而不断失败,但在使用相对路径(./users/..").我这里的配置有问题吗?
I have a quite new NestJS application. I'm trying to run unit tests, but they keep failing due to 'cannot find module..' when using absolute paths ("src/users/..."), but works when using relative paths ("./users/.."). Is there anything wrong with my configuration here?
package.json 中的 Jest 设置:
Jest setup in package.json:
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".spec.ts$",
"transform": {
"^.+\.(t|j)s$": "ts-jest"
},
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
tsconfig.json:
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 配置.
I had the same issue, the problem was the default jest configuration created by Nestjs.
我将 "rootDir": "src"
更改为 "rootDir": "./"
并添加 "modulePaths":['
.
I changed "rootDir": "src"
to "rootDir": "./"
and add "modulePaths": ['<rootDir>']
.
最后,我的 jest 配置如下所示:
Finaly, my jest configuration looks like this:
moduleFileExtensions: ['js', 'json', 'ts'],
rootDir: './',
modulePaths: ['<rootDir>'],
testRegex: 'spec.ts$',
transform: {
'^.+\.(t|j)s$': 'ts-jest'
},
coverageDirectory: './coverage',
testEnvironment: 'node',
如果您的配置有一些相对路径,您可能需要更新它们,因为您的 rootDir
不再是 src
.
If you have some relative paths to your config you will probably have to update them because your rootDir
is not src
anymore.
如果您在 package.json
中设置了 jest 配置,或者如果配置文件位于项目的根目录,您甚至可以删除 rootDir
,如文档:https://jestjs.io/docs/en/configuration#rootdir-string一个>
You can even remove rootDir
is you setup the jest config in package.json
or if the config file is located at the root of your project, as explained in the doc: https://jestjs.io/docs/en/configuration#rootdir-string
如果您想了解 modulePaths
:https://jestjs.io/docs/en/configuration#modulepaths-arraystring
希望它也适用于您.
这篇关于NestJS Jest 找不到具有绝对路径的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!