NestJS Jest无法找到具有绝对路径的模块

时间:2020-09-23 12:34:55

标签: node.js jestjs nestjs ts-jest

我有一个相当新的NestJS应用程序。我正在尝试运行单元测试,但是由于使用绝对路径(“ src / users / ...”)时,由于“无法找到模块..”,它们仍会失败,但是使用相对路径(“ ./users/ ..”)。我的配置这里有问题吗?

package.json中的最佳设置:

"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
  }
}

2 个答案:

答案 0 :(得分:3)

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

我将"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中设置了jest的配置,或者如果配置文件位于项目的根目录,您甚至可以删除package.json,如doc中所述:https://jestjs.io/docs/en/configuration#rootdir-string < / p>

如果您想了解有关modulePaths的信息:https://jestjs.io/docs/en/configuration#modulepaths-arraystring

希望它也对您有用。

答案 1 :(得分:0)

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

如果要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
}