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

20

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

你的问题是否类似于这个 https://dev59.com/8VMHtIcB2Jgan1zn51ze#63716954? - tmhao2005
5个回答

41

我遇到了同样的问题,问题出在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
如果您在package.json中设置了jest配置或者配置文件位于项目根目录下,您甚至可以删除rootDir,如文档所述:https://jestjs.io/docs/en/configuration#rootdir-string 如果您想了解有关modulePaths的详细信息,请访问:https://jestjs.io/docs/en/configuration#modulepaths-arraystring 希望这也适用于您。

5
请注意,此配置可以在 package.json 中找到。大多数由 Nest 预先配置的 Jest 配置是相同的。对于我来说,我只需要更改 rootDir 并添加如上所示的 modulePaths 就能使其正常工作。 - Jaap Weijland
这对我起作用了。 - jseashell
如果你有类似于@shared或者任何类似于@的东西,请检查moduleNameMapper以使其解析。 - giovannipds

31

我的具体问题

我在使用 NestJS 进行端对端测试时遇到了这个问题。我设置了从项目根目录开始的绝对路径。以下是我的 tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "paths": {
      "src/*": ["./src/*"]
    },
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": false,
    "noImplicitAny": false,
    "strictBindCallApply": false,
    "forceConsistentCasingInFileNames": false,
    "noFallthroughCasesInSwitch": false
  }
}


以下是解决我的问题的方法。

test/jest-e2e.config.js 中添加 moduleDirectories: ['<rootDir>/../', 'node_modules']

test/jest-e2e.config.js 的工作正常。

{
  moduleFileExtensions: ['js', 'json', 'ts'],
  rootDir: '.',
  testEnvironment: 'node',
  testRegex: '.e2e-spec.ts$',
  transform: {
    '^.+\\.(t|j)s$': 'ts-jest',
  },
  moduleDirectories: ['<rootDir>/../', 'node_modules'],
};

注意: moduleDirectories选项应该是相对于Jest配置文件的路径,必须从<rootDir>开始并根据需要返回。 有关详细信息,请访问https://github.com/nestjs/nest/issues/5522#issuecomment-714592183
如果您想查看我的存储库,请访问以下链接。 https://github.com/mabdullahadeel/nest-bookmarker

1
不明白为什么需要 node_modules,但它确实起作用了。谢谢。 - Matthis Kohli

11

您需要通过配置moduleNameMapper来配置jest解析模块路径。

package.json

    {  
      "jest": {
                // ...
        "rootDir": "src",
        "moduleNameMapper": {
          "^src/(.*)$": "<rootDir>/$1"
        },
      }
    } 

对我有用 - 在NestJS引导配置中似乎仍然没有修复... :-/ - mmey

7

就我的情况而言

"moduleDirectories": ["<rootDir>/../", "node_modules"]

需要在/test/jest-e2e.json中指定,这样问题就解决了。


我刚遇到了同样的问题。这个答案确实解决了问题。 - Noldorin Zhang

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
}

仍然无法工作。 - Udhayakumar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接