19

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
  }
}
skyboyer
  • 22,209
  • 7
  • 57
  • 64
Chris Eikrem
  • 496
  • 1
  • 5
  • 20
  • Is your question similar to this https://stackoverflow.com/questions/63709973/jest-test-runs-cannot-find-module-error/63716954#63716954? – tmhao2005 Sep 23 '20 at 15:07

5 Answers5

40

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.

GreenMonkeyBoy
  • 624
  • 4
  • 2
  • 5
    Note that this configuration can be found in `package.json`. Most of the pre-configured configuration of jest by Nest is the same. For me, I only had to alter the `rootDir` and add `modulePaths` as depicted above to make it work. – Jaap Weijland Jan 27 '21 at 15:09
  • This worked for me – jseashell Oct 20 '21 at 01:04
  • If you have something like `@shared` or anything like `@`, check `moduleNameMapper` to make it resolve that. – giovannipds Dec 10 '21 at 16:26
24

I spent a lot of time searching and figuring this problem out.

My Specific Issue

I faced this issue when running e2e tests with NestJS. I set up the absolute path from the root of the project. Here is my 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
  }
}


Here is what solved my problem.

add moduleDirectories: ['<rootDir>/../', 'node_modules'] to test/jest-e2e.config.js.

working 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'],
};

NOTE: moduleDirectories options should be paths relative to the jest confi g file, it is necessary to start you path from <rootDir> and go back as needed. For details of this visit https://github.com/nestjs/nest/issues/5522#issuecomment-714592183


Here is the link to my repo if you want to have a look at it. https://github.com/mabdullahadeel/nest-bookmarker


abdadeel
  • 446
  • 5
  • 8
11

You need to configure how jest resolves module paths by configuring the moduleNameMapper.

package.json

    {  
      "jest": {
                // ...
        "rootDir": "src",
        "moduleNameMapper": {
          "^src/(.*)$": "<rootDir>/$1"
        },
      }
    } 
  • Worked for me - still doesn't seem to be fixed in the NestJS bootstrap configuration... :-/ – mmey Nov 11 '22 at 11:22
6

in my case the

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

needed to be specified in the /test/jest-e2e.json, that fixed the issue

Kosti
  • 106
  • 1
  • 4
2

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
}
arturataide
  • 363
  • 2
  • 11