Why are my Typescript paths not resolving during the execution of Jest?

I am currently in the process of transitioning this project to jest by following these specific instructions. Everything seems to be working fine except for the files that make use of the paths configuration:

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

It appears that during the execution of tests, the import statements are unable to resolve and the following error 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 workaround to instruct jest/ts-jest to include the @paths when resolving imports?

Answer №1

I had a challenge of resolving modules paths that start with ~/ to the format of

<baseUrl>/<moduleName>
.

Special thanks to OJ Kwon for providing the solution (kudos to him).

Updating tsconfig.json

Please refer to the module-resolution path-mapping documentation to implement the changes.

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

Configuring Jest

In order to ensure that jest also resolves the paths correctly, you need to make adjustments in the configuration as shown below:

"moduleNameMapper": {
  "~/(.*)": "<rootDir>/src/$1"
},

Answer №2

To include jest.config.js in the root project folder, add the following code:

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

Ensure that your tsconfig.json file contains a paths field like this one:

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

Answer №3

When using Jest, it is unable to recognize tsconfig's path mapping during typescript compiler time. Therefore, the Jest configuration needs to include a compatible modulenamemapper in order to resolve any aliased paths.

Answer №4

Thanks to @FranSanchis for helping me resolve the issue. I made some modifications to align with the 2023 jest changes.

Update in jest.config.js

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

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

Also, update in tsconfig file:

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

Answer №5

Configuration Files

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

Unit Test Package Configuration

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

End-to-End Test Package Configuration

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountered a glitch while compiling Nestjs using typeorm

I encountered an issue when attempting to include the entity.ts in the project Here is the content of ts file: import { Column, Entity, PrimaryGeneratedColumn } from "typeorm" @Entity('Usuario') export class UsuarioIdentity { @Pr ...

In TypeScript, there is a mismatch between the function return type

I am new to TypeScript and trying to follow its recommendations, but I am having trouble understanding this particular issue. https://i.stack.imgur.com/fYQmQ.png After reading the definition of type EffectCallback, which is a function returning void, I t ...

The inference of conditional types varies when used with generic types

When a generic type is passed, TypeScript infers the conditional type (with disabled distribution) in a different way. type Box<T> = { a: T }; // Conditional type with disabled distribution using tuple. type CondType<T> = [T] extends [string | ...

Encountering a Difficulty while attempting to Distinguish in Angular

I am currently working on a form where I need to dynamically add controls using reactiveForms. One specific task involves populating a dropdown menu. To achieve this, I am utilizing formArray as the fields are dynamic. Data: { "ruleName": "", "ruleD ...

The JsonFormatter is throwing an error because it is trying to access the property 'on' of an undefined variable

I have encountered an error while attempting to generate an HTML report using cucumber-html-reporter The error message is: Unhandled rejection TypeError: Cannot read property 'on' of undefined at new JsonFormatter (C:\path-to-project\ ...

When attempting to access http://localhost:3000/traceur in Angular 2 with the angular-in-memory-web-api, a 404 (Not Found) error

Hello, I'm encountering an issue with angular-in-memory-web-api. I have attempted to use angular2-in-memory-web-api in SystemJS and other solutions, but without success. I am currently using the official quickstart template. Thank you for any assistan ...

Mistakes following update to Angular 4 from Angular 2

After upgrading from Angular2 to Angular4, I encountered these errors in the CLI. While my app continues to function after the upgrade, I am curious about possible solutions to resolve these errors. Any suggestions? https://i.stack.imgur.com/CyYqw.png He ...

Is there a way to obtain a unique response in TestCafe RequestMock?

With Testcafe, I have the capability to simulate the response of a request successfully. I am interested in setting up a caching system for all GET/Ajax requests. The current setup functions properly when the URL is already cached, but it fails to prov ...

Issues arising when routing ffmpeg to flac encoder

I am facing an issue with encoding a flac file with seektables. The ffmpeg's flac encoder does not include seektables, so I have to resort to using the flac Command Line Interface (CLI). My goal is to convert any arbitrary audio file into a seekable f ...

Why is the quantity of my item being increased? My method is adding it when it shouldn't be

I have a project in Angular that involves an online store. However, every time I click the button "agregar a carrito" (add to cart in Spanish), my item's quantity seems to increase inexplicably. ts. removeItem(item: iProduct) { if (item.quantity ...

Show the JSON data items in a React Native application

In my React Native application, I am dealing with a JSON file containing various data sets. One of the challenges I am facing is extracting specific information from this JSON and displaying it correctly. [ { "001": [ { " ...

Previewing multiple selected files in Angular interface

As a newcomer to Angular, I am currently working on a feature that involves selecting multiple files and displaying their previews before uploading them to the server. While my code works correctly when individual files are selected one at a time, it fail ...

Transform data into JSON format using the stringify method

I am facing an issue with my TypeScript code where I need to retrieve specific information from a response. Specifically, I want to output the values of internalCompanyCode and timestamp. The Problem: An error is occurring due to an implicit 'any&apo ...

Adjust dropdown options based on cursor placement within textarea

I have a textarea and a dropdown. Whenever a user selects an option from the dropdown menu, it should be inserted into the text area. However, I am facing a bug where the selected value is being inserted at the end of the text instead of at the current cur ...

What is the best way to configure the default entry point for a package.json file in a React

I'm having trouble with the default export in my package.json file. when I try to import: import { Component } from 'packagename/'; // size 22kb or import { Component } from 'packagename/dist' // size 22kb; but import { Component ...

Top tips for handling HTML data in JSON format

I'm looking to fetch HTML content via JSON and I'm wondering if my current method is the most efficient... Here's a sample of what I'm doing: jsonRequest = [ { "id": "123", "template": '<div class=\"container\"&g ...

The dynamic concatenation of Tailwind classes is failing to have any effect, even though the full class name is being

I'm currently using Tailwind CSS within my Next.js project and I have a common method that dynamically returns the desired background color. However, despite adding the full class name, the background color is not displaying as expected. After reading ...

What is the best way to insert an item into a tree structure when determining the appropriate level for insertion is necessary beforehand?

Currently, I am dealing with a tree-like object structure: interface Node { id: number; name: string; children?: Node[]; } NODE_DATA: Node[] = [ { id: 1, name: 'A' }, { id: 2, name: 'B', children: [ ...

What is the process of incorporating a JavaScript node module into TypeScript?

Having trouble importing the xml2js module as I keep getting a 404 error stating that it's not found. import xml2js from 'xml2js'; Any suggestions on how to properly import JavaScript modules located in the node_modules directory when work ...

When checking for a `null` value, the JSON property of Enum type does not respond in

Within my Angular application, I have a straightforward enum known as AlertType. One of the properties in an API response object is of this enum type. Here is an example: export class ScanAlertModel { public alertId: string; public alertType: Aler ...