NestJS Jest无法找到具有绝对路径的模块 [英] NestJS Jest cannot find module with absolute path

查看:405
本文介绍了NestJS Jest无法找到具有绝对路径的模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相当新的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 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创建的默认玩笑配置.

I had the same issue, the problem was the default jest configuration created by Nestjs.

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

最后,我的笑话配置如下:

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,如doc中所述:

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/zh-CN/configuration#modulepaths-arraystring

And if you want read about modulePaths: https://jestjs.io/docs/en/configuration#modulepaths-arraystring

希望它也对您有用.

这篇关于NestJS Jest无法找到具有绝对路径的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆