Solve the TypeScript path when using jest.mock

I am currently in the process of adding unit tests to a TypeScript project that utilizes compilerOptions.paths. My goal is to mock an import for testing purposes.

However, I have encountered an issue where jest is unable to resolve the module to be mocked.

 FAIL  logic/index.test.ts
  ● Test suite failed to run

    Cannot find module '@lib/foo' from 'logic/index.test.ts'

The project is using ts-jest, which does support paths in imports. It seems like there might be an extra step needed for mocking imports.

What would be the correct approach to resolve this path-related problem?


SIMPLIFIED CASE

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

Filesystem

* lib
  * __mocks__
    * foo.ts
  * foo.ts
* logic
  * index.ts
  * index.test.ts
* tsconfig.json
* jest.config.js
// index.ts
import foo from '@lib/foo';

const logic = () => foo();

export default logic;
// index.test.ts
import 'jest';

import logic from '.';

jest.mock('@lib/foo');
// jest.config.js
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
};

Answer №1

As per the guidelines provided in the documentation of ts-jest, it is important to ensure that Jest's moduleNameMapper is updated accordingly when utilizing compilerOptions.paths. The library offers a convenient utility function to create the appropriate mapping for this purpose:

// jest.config.js
const { pathsToModuleNameMapper } = require('ts-jest/utils');

const { compilerOptions } = require('path/to/tsconfig');

module.exports = {
  moduleNameMapper: pathsToModuleNameMapper(
    compilerOptions.paths,
    { prefix: '<rootDir>/' },
  ),
  preset: 'ts-jest',
  testEnvironment: 'node',
};

Alternatively, if preferred, you can manually define the mappings like so:

// jest.config.js
module.exports = {
  moduleNameMapper: { '^@lib/(.*)$': '<rootDir>/lib/$1' },
  preset: 'ts-jest',
  testEnvironment: 'node',
};

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

Looking to modify the height and width of an image when it is hovered over using inline CSS

My current project involves working with a dynamic template where the HTML code is generated from the back-end using TypeScript. I am trying to implement inline CSS on hover, but despite having written the necessary code, it does not seem to work as intend ...

When implementing Angular 6, using a shared module within individual lazy-loaded modules can lead to a malfunctioning app when changes are

Hey there, I've encountered a strange problem that didn't occur when I was using Angular 5. Let me explain the situation: In my App routing module, I have: { path: 'moduleA', pathMatch: 'full', loadChildren: &ap ...

Issues arise in TypeScript 5.1.3 with lodash due to type errors involving excessively deep type instantiation, which may potentially be infinite

Recently, I made updates to my Ionic/Angular project and now it is running Angular version 16.1.3 along with TypeScript version 5.1.3. In addition to this, my project also includes the following dependencies: "lodash-es": "^4.17.21", ...

Dealing with Typescript Errors in Ionic3: How to Handle "Property 'x' does not exist on value of type 'y'" Issues

I stumbled upon this particular post (and also this one) while searching for a solution to my issue. I am looking to suppress these specific errors: 'Payload' property is missing from the 'Matatu' type. 'Key' property is no ...

Configuring ESLint and Prettier with the Airbnb style guide for TypeScript in a React Native (Expo) project

I have been struggling with setting up linting and formatting for my React Native project for a while now. Despite following various tutorials, I still encounter setup issues. My project consists of a Django backend and a React Native frontend. I began im ...

Combining HTML with multiple .ts files in Angular

I've been dedicating time to enhancing an Angular application, particularly a sophisticated table with intricate styling and functionality. Within my component file, there is a whopping 2k lines of code that includes functions for text formatting, ta ...

Express string declaration in a single TypeScript line

const restrictString = (str: string): string => str.match(/[ab]/g)?.join('') || '' Is there a way to restrict a string to only contain the characters 'a' and 'b' in a one-liner function? I am aware that this can ...

Exploring the process of linking MatPaginator to a server-sourced datasource within an Angular Material table

In my Angular 5 project, I am utilizing Angular Material table to create a grid. The data is fetched from an HTTP request and stored in a variable named dataSourceNew within the view.ts file. Since dataSourceNew has dynamic content and structure, no interf ...

What is the process through which Typescript determines the property types of union types?

I am implementing a unique set of types to enable angular form typing: import { FormArray, FormControl, FormGroup } from '@angular/forms'; export type DeepFormArray<T, U extends boolean | undefined = undefined> = T extends Array<any> ...

What steps should I take to fix this TypeScript error?

I've been struggling to fix this error, but I'm unsure of the best way to resolve it. Here is the code snippet I've been working with: Here is the specific error message: ...

Establish a Svelte and TypeScript "observe" script for developing vscode extensions

Hi there! As a newbie in TypeScript, Svelte, and VSCode extension development, I have my first question to ask ...

The Angular router is directed to an empty URL path instead of the specified URL

I have encountered a strange issue while developing my angular app which involves the router functionality. All routes were working perfectly fine until I discovered that after a successful login, instead of navigating to the '/admin' path as int ...

Exploring Vue through algorithm testing with Jest

I'm working with a component that has the following structure. How can I create a Vue Jest test that meets these specific requirements? <template> <div align="center"> <button @click="Tests()">Tests</butt ...

When attempting to declare a functional component in React utilizing styled-components in TypeScript, an error is encountered stating "No overload matches this call."

Playground https://codesandbox.io/s/typescript-type-checking-question-0b42t Sample Code type BadgeTypes = { success: string; secondary: string; alert: string; text: string; }; type Theme = { fonts?: object; borderRadius: string; primary?: o ...

Leveraging Shared Modules Component across multiple modules in Angular can enhance code re

In my project structure, I have a shared folder containing shared.module.ts. Additionally, there is a modules folder with sub-modules, one of which is Dashboard.module.ts. Inside the shared module, I created a custom sidebar menu that I intend to use withi ...

"Creating a mock for the appModel method that returns a specific value from the Auth

Currently, I am working on testing a controller method that relies on an AppModel method to retrieve the account of the currently logged-in user. The issue I'm facing is my inability to properly mock the AppModel method to supply the account_id, which ...

Just starting out with TypeScript and running into the error: "Cannot assign type 'null' to type 'User[]'"

Why is TypeScript giving me an error message here? const dispatch = useAppDispatch(); useEffect(() => { onAuthStateChanged(auth, (user) => { dispatch(getUser(user)); }); }, [dispatch]); Error: Argument of type 'User | nul ...

Unable to retrieve nested objects from HTTP Response

After receiving data from a HTTP Response, I am trying to access and display it in my template. However, despite storing the data into a component variable, I am encountering issues when trying to access specific properties of the object. { "files": [ ], ...

Route user based on login status using router

I want to set up automatic routing to a login page for users who are not logged in. app.module.ts import { RouterModule, Routes } from '@angular/router'; import { AppComponent } from './app.component'; import { LoginComponent } from &ap ...

Using TypeScript to test a Vue3 component that includes a slot with Cypress

I'm currently facing challenges setting up a new project. The technologies I am using include Vue3, TypeScript, and Cypress. It seems like the problem lies within the TypeScript configuration. Below is a Minimal Working Example (MWE) of my setup. Any ...