NestJS Jest cannot find module with absolute path

前端 未结 2 498
臣服心动
臣服心动 2021-01-23 12:22

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/...")

相关标签:
2条回答
  • 2021-01-23 13:04

    I believe you are missing the rootDir in your tsconfig.json

    If you want to import { ... } from 'src/..., the rootDir needs to be equal to ./.

    Check this example:

    {
    "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
    }
    
    0 讨论(0)
  • 2021-01-23 13:15

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

    I changed "rootDir": "src" to "rootDir": "./" and add "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',
    

    If you have some relative paths to your config you will probably have to update them because your rootDir is not src anymore.

    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

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

    Hope it will also work for you.

    0 讨论(0)
提交回复
热议问题