【问题标题】:NestJS Jest cannot find module with absolute pathNestJS Jest 找不到具有绝对路径的模块
【发布时间】:2021-01-09 15:55:18
【问题描述】:

我有一个全新的 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
  }
}

【问题讨论】:

标签: node.js jestjs nestjs ts-jest


【解决方案1】:

我遇到了同样的问题,问题是 Nestjs 创建的默认 jest 配置。

我将"rootDir": "src" 更改为"rootDir": "./" 并添加"modulePaths": ['<rootDir>']

最后,我开玩笑的配置是这样的:

  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

如果你想了解modulePathshttps://jestjs.io/docs/en/configuration#modulepaths-arraystring

希望它也对你有用。

【讨论】:

  • 注意这个配置可以在package.json找到。 Nest 对 jest 的预配置大部分是相同的。对我来说,我只需要更改 rootDir 并添加 modulePaths 即可,如上图所示。
  • 这对我有用
  • 如果您有类似@shared 或类似@ 的内容,请检查moduleNameMapper 以使其解决。
【解决方案2】:

我相信您在tsconfig.json 中缺少rootDir

如果你想import { ... } from 'src/...rootDir需要等于./

检查这个例子:

{
"moduleFileExtensions": [
    "ts",
    "tsx",
    "json",
    "js"
],
"rootDir": "./",
"testRegex": ".spec.ts$",
"collectCoverageFrom": ["**/*.ts", "!**/node_modules/**"],
"coverageDirectory": "./coverage",
"coverageReporters": ["html", "text", "text-summary"],
"preset": "ts-jest",}



  "compilerOptions": {
  "module": "commonjs",
  "declaration": true,
  "removeComments": true,
  "emitDecoratorMetadata": true,
  "experimentalDecorators": true,
  "allowSyntheticDefaultImports": true,
  "target": "es2017",
  "sourceMap": true,
  "outDir": "./dist",
  "rootDir": "./",
  "baseUrl": "./",
  "incremental": true
}

【讨论】:

    猜你喜欢
    • 2022-11-07
    • 2018-10-14
    • 1970-01-01
    • 2018-11-24
    • 2019-09-04
    • 2021-08-25
    • 2022-07-15
    • 1970-01-01
    相关资源
    最近更新 更多