node.js - NestJS Jest 找不到具有绝对路径的模块

标签 node.js jestjs nestjs ts-jest

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

相关文章:

javascript - 如何从 WhatsApp 位置共享中检索位置坐标?

javascript - 找不到入口模块和 webpack 中的错误

javascript - 在 Jest 中使用 'new' 关键字模拟外部服务

typescript - 新的 Nestjs 应用程序上的 Webpack Typescript 错误

Nestjs 请求和应用程序生命周期

javascript - BitGO - 从对象数组中获取帐户和值(value)

node.js - 没有从 Laravel 中的 Redis 发布功能获取消息

reactjs - 如何测试 global.i18n.t

javascript - React Native Jest 测试 : TypeError: Cannot read property 'unsubscribeFromTopic' of undefined

node.js - Expect(spiedMethod).not.toBeCalled() 失败,因为它正在被另一个测试调用