npmnode.js95% confidence\u2191 27

NestJS Jest cannot find module with absolute path

Full error message
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?

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:

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true
  }
}

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.

API access

Get this solution programmatically \u2014 free, no authentication.

curl https://depscope.dev/api/error/78b81c26002c0770dd0398afa9941054978bbfbfd33c814d5991f6924266f147
hash \u00b7 78b81c26002c0770dd0398afa9941054978bbfbfd33c814d5991f6924266f147
NestJS Jest cannot find module with absolute path — DepScope fix | DepScope