71

Attempting to convert this project over to jest using these instructions. I have everything working except for the files that use the paths configuration:

"paths": {
      "@fs/*": ["./src/*"], 
      "@test/*": ["./test/*"]
    }

It looks as if when the tests are run the import statements do not resolve and this is logged:

Cannot find module '@fs/container/validation/ValidationContext' from 'Core.spec.ts'

  1 | import { ValidationOptions } from "@fs/container/validation/ValidationOptions";
> 2 | import { ValidationContext } from "@fs/container/validation/ValidationContext";
    | ^
  3 | import { ValidationContainer } from "@fs/container/validation/ValidationContainer";
  4 | 
  5 | import { Core1 } from "@test/core/Core1";

  at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:221:17)
  at Object.<anonymous> (test/core/Core.spec.ts:2:1)

Is there a way to get jest/ts-jest include the @paths while resolving imports?

6 Answers 6

85

I wanted to resolve modules paths starting with ~/ to my <baseUrl>/<moduleName>.

Thank to OJ Kwon link I solved it with (give him point).

tsconfig.json

see module-resolution path-mapping doc

{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "~/*": ["*"]
    }
  },
}

jest config

Then we need to tell jest to resolve the paths too. It's done with the following config:

"moduleNameMapper": {
  "~/(.*)": "<rootDir>/src/$1"
},
Sign up to request clarification or add additional context in comments.

2 Comments

It helped me a lot in my case my ts path was "@data/*": ["src/data/*"] then in my jest config i added: '@data/(.*)': '<rootDir>/src/data/$1',
If you set rootDir to src then you don't need to remove src from here.
44

Add jest.config.js on root project folder with the content below.

const { pathsToModuleNameMapper } = require('ts-jest');
const { compilerOptions } = require('./tsconfig');
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: "<rootDir>" }),
  modulePaths: ['<rootDir>'],
  coverageDirectory: '../coverage',
  moduleFileExtensions: ['js', 'json', 'ts'],
  testRegex: '.*\\.spec\\.ts$',
  transform: { '^.+\\.(t|j)s$': 'ts-jest' },
  collectCoverageFrom: ['**/*.(t|j)s'],
};

Also make sure that your tsconfig.json file has a paths field, like this:

{
  "compilerOptions": {
    ....,
    "paths": {
      "src/*": ["src/*"]
    }
  },
}

7 Comments

what is ts-jest/utils?
const { pathsToModuleNameMapper } = require('ts-jest'). See kulshekhar.github.io/ts-jest/docs/getting-started/paths-mapping/…
No longer works
I had to add the prefix parameter to get it to work: pathsToModuleNameMapper(compilerOptions.paths, { prefix: "<rootDir>" }).
A baseUrl should be took in account: { prefix: `<rootDir>${compilerOptions.baseUrl}` }
|
32

jest can't honor tsconfig's path mapping as it's ts compiler time, so jest configuration should have corresponding modulenamemapper to resolve aliased paths.

1 Comment

Link only answers are discouraged
5

Answer By @FranSanchis did fix the issue for me, I have just done a lot bit of changes to meet with 2023 jest changes

in jest.config.js

const { pathsToModuleNameMapper } = require('ts-jest');
const { compilerOptions } = require('./tsconfig');

module.exports = {
  
  preset: 'ts-jest',
.
.
.
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),
  modulePaths: ['<rootDir>'],
}

And in tsconfig

"compilerOptions": {
    "target": "es6",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }

Comments

4

tsconfig.json

"compilerOptions": {
  "baseUrl": "./",
  "paths": {
    "@/*": ["src/*"]
  }
}

package.json (for unit test)

"jest": {
  "rootDir": ".",
  "testRegex": "/test/.*\\.spec\\.ts$",
  "moduleNameMapper": {
    "@/(.*)": "<rootDir>/src/$1"
  }
}

jest-e2e.json (for e2e test)

{
  "rootDir": "../",
  "testRegex": "/test/.*\\.e2e-spec\\.ts$",
  "moduleNameMapper": {
    "@/(.*)": "<rootDir>/src/$1"
  }
}

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
0

For me Jest complained that it can't find the module e.g. project/feature-1 in an angular 18 project.

I needed to do the mapping 3 times to make it work:

  1. In the tsconfig.json
  2. In the tsconfig.spec.json
  3. In the jest.config.ts

Here's what worked for me: tsconfig.json and tsconfig.spec.json:

"paths": {                                          
  "project/*": ["./packages/project/src/*/public_api"],
},

jest.config.ts:

import type { Config } from 'jest';

const config: Config = {
    preset: 'jest-preset-angular',
    moduleNameMapper: {
        '^project/(.*)': '<rootDir>/packages/project/src/$1/public_api'
    },
    setupFilesAfterEnv: ['<rootDir>/setup-jest.ts']
};

export default config;

For the sake of completeness also the setup-jest.ts:

import { setupZoneTestEnv } from 'jest-preset-angular/setup-env/zone';

setupZoneTestEnv();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.