Ole
Ole

Reputation: 47212

Typescript paths not resolving when running jest?

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?

Upvotes: 65

Views: 45180

Answers (6)

FranSanchis
FranSanchis

Reputation: 1701

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/*"]
    }
  },
}

Upvotes: 43

Juri Sinitson
Juri Sinitson

Reputation: 1635

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();

Upvotes: 0

sudo-rm-rf
sudo-rm-rf

Reputation: 31

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"
  }
}

Upvotes: 3

Aran Tamool
Aran Tamool

Reputation: 319

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/*"]
    }

Upvotes: 4

OJ Kwon
OJ Kwon

Reputation: 4661

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.

Upvotes: 30

&#201;douard Lopez
&#201;douard Lopez

Reputation: 43419

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"
},

Upvotes: 83

Related Questions