Using path aliases in a Typescript project with Typescript + Jest is not a viable option

Note

  1. I am able to use aliases in my TypeScript file.
  2. Unfortunately, I cannot use aliases in my test files (*.test.ts).

My Configuration

1. Jest.config.ts

import type { Config } from '@jest/types';

const config: Config.InitialOptions = {
  verbose: true,
  preset: 'ts-jest',
  clearMocks: true,
  collectCoverage: true,
  coverageDirectory: 'tests/coverage',
  collectCoverageFrom: ['<rootDir>/src/**/*.ts?'],
  coverageProvider: 'v8',
  moduleFileExtensions: [
    'js',
    'mjs',
    'cjs',
    'jsx',
    'ts',
    'tsx',
    'json',
    'node',
  ],
  rootDir: '.',
  moduleNameMapper: {
    '/^@(.*)$': '<rootDir>/src/$1',
  },
  modulePathIgnorePatterns: ['tests/coverage'],
  testMatch: ['**/tests/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[tj]s?(x)'],
  testEnvironment: 'node',
};

export default config;

2. tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["ESNext", "DOM", "es5", "es2015.promise"],
    "baseUrl": "./",
    "module": "esnext",
    "sourceMap": true,
    "moduleResolution": "node",
    "noImplicitAny": true,
    "allowSyntheticDefaultImports": true,
    "typeRoots": ["./node_modules/@types/"],
    "types": ["jest", "node"],
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules", "**/*.spec.ts"]
}

When I execute this command in the terminal:

jest --config ./jest.config.ts --coverage

My Test Failed:

https://i.stack.imgur.com/fJOyv.png

What happened? I have configured it in jest.config.ts.

moduleNameMapper: {
  '/^@(.*)$': '<rootDir>/src/$1',
},
  1. The first time out of my TypeScript type check output.

https://i.stack.imgur.com/IzHiu.png

I can't believe it. There was a statement recently - why is it happening now? Please help me.

Answer №1

moduleNameMapper: {
  '/^@(.*)$': '<rootDir>/src/$1', // Defines an alias similar to webpack.resolve.alias
},

Based on the explanation above

import { add } from '@/add/add'

The correct way to write it is:

import { add } from '@add/add'

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

How to utilize *ngFor alongside the async pipe for conditional rendering in Angular 8 HTML

.html <ng-container *ngFor="let contact of listContact | async; let index = index;"> <h6 class="title" *ngIf="contact && contact['type']"> {{contact['type']}} </h6> <div> {{conta ...

Steps for preventing text manipulation in ng2-ace-editorWould you like to restrict users from copying, pasting

How can I prevent users from copying, pasting, and dropping text in ng2-ace-editor? https://github.com/fxmontigny/ng2-ace-editor is the library I implemented in my Angular 5 application. ...

My component is missing the ChangeDetectorRef in Nativescript

I am attempting to automatically update an array within a Listview by utilizing ChangeDetectorRef in the following way: import { Component, OnInit, ChangeDetectionStrategy, Input, ChangeDetectorRef } from "@angular/core"; @Component({ selector: "regi ...

Using sl-vue-tree with vue-cli3.1 on internet explorer 11

Hello, I am a Japanese individual and my proficiency in English is lacking, so please bear with me. Currently, I am using vue-cli3.1 and I am looking to incorporate the sl-vue-tree module into my project for compatibility with ie11. The documentation menti ...

What is the abbreviation for a 'nested' type within a class in TypeScript?

Consider the TypeScript module below: namespace AnotherVeryLongNamespace { export type SomeTypeUsedLater = (a: string, b: number) => Promise<Array<boolean>>; export type SomeOtherTypeUsedLater = { c: SomeTypeUsedLater, d: number }; } cl ...

Implement a global interceptor at the module level in NestJS using the Axios HttpModule

Is there a way to globally add an interceptor for logging outgoing requests in Angular? I know I can add it per instance of HttpService like this: this.httpService.axiosRef.interceptors.request.use((config) => ...) But I'm looking to add it once a ...

What could be the reason for the Express function Router() returning a value of undefined?

Currently, I am working with TypeScript and Express to develop an API that adheres to the principles of Clean Architecture. To organize my application, I have structured each route in separate folders and then imported them all into an index.ts file where ...

Ensuring the type of a specific key in an object

Seeking a more stringent approach regarding object keys in TypeScript. type UnionType = '1' | '2' | '3' type TypeGuardedObject = { [key in UnionType]: number } const exampleObject: TypeGuardedObject = { '1': 1, ...

Angular 2: Store all form inputs within a JSON object upon submission

I am working on a form that has multiple fields and I need to retrieve the data once it is submitted. This is the code in component.html : <div class="ui raised segment"> <h2 class="ui header">Demo Form: Sku</h2> <form #f="ngFor ...

Building a dynamic hierarchical list in Angular 8 with recursive expansion and collapse functionality

I am attempting to construct a hierarchical expand/collapse list that illustrates a parent-child relationship. Initially, the parent nodes will be displayed. If they have children, a carat icon is shown; otherwise, a bullet icon appears. When the carat ico ...

Validating the end points of a Node Express API integrated with MySql

Currently, I am developing an API using express that interacts with a MySQL database to store user credentials securely. One of the main functionalities of my API includes endpoints for user registration and login. Testing these endpoints in Postman has s ...

Challenges with importing and using jspdf and autotable-jspdf in Angular 8

Issue with Generating PDF Using Angular 8, JSPDF, and JSPDF-AutoTable I am facing a challenge with exporting/generating a PDF based on an HTML grid. I need to make some DOM changes with CSS, remove toggle buttons, alter the header, etc. However, all the s ...

Creating QR codes from raw byte data in TypeScript and Angular

I have developed a basic web application that fetches codes from an endpoint and generates a key, which is then used to create a QR Code. The key is in the form of an Uint8Array that needs to be converted into a QR Code. I am utilizing the angularx-qrcode ...

A TypeScript generic function designed to accept either two arrays or two objects, but not a combination of both

Currently, I am creating an extend function in TypeScript that has the capability to: Update the first object with the keys/values of the second when given two objects. Append the elements of the second array to the first array when provided with two arr ...

Is it possible to incorporate regular React JSX with Material UI, or is it necessary to utilize TypeScript in this scenario?

I'm curious, does Material UI specifically require TypeScript or can we use React JSX code instead? I've been searching for an answer to this question without any luck, so I figured I'd ask here. ...

Discovering the array item by its ID using Angular 2 with Typescript

Hey everyone, I'm currently working with asp.net mvc 5 and running into an issue. When attempting to retrieve an object by its id, it keeps returning undefined. The strange thing is that the objects display fine when checking console.log(this.vtypes). ...

The method this.$el.querySelector does not exist

The data retrieved from the database is inserted into the input fields and submitted as a form. This data is an object that passes the value to the database. However, when I trigger this form, an error occurs. See example of the error <input id=" ...

Tips for accessing and adjusting an ngModel that is populated by an attribute assigned via ngFor

Looking for guidance on how to modify an input with ngModel attribute derived from ngFor, and update its value in the component. Here is my code snippet for reference: HTML FRONT The goal here is to adjust [(ngModel)] = "item.days" based on button click ...

Bring in a function by its name from the ts-nameof package that is not declared in the d.ts export

Recently, I came across a captivating package that caught my interest and I would love to incorporate it into my TypeScript application: https://github.com/dsherret/ts-nameof However, upon attempting to import the nameof function, I realized it was not be ...

Define an object type in Typescript that includes both specified properties and an unlimited number of unspecified properties

I'm attempting to create a custom data type using the code below, but it's not working: type CustomDataType { [key: string]: CustomDataType; isValid: boolean; errors?: string[]; } My goal is to have a CustomDataType with an isValid propert ...