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

Understanding and processing HTML strings in typescript

I am currently utilizing TypeScript. Within my code, there is an object named "Reason" where all variables are defined as strings: value, display, dataType, and label. Reason = { value: '<ul><li>list item 1</li><li&g ...

"What is the significance of the .default property in scss modules when used with typescript

When dealing with scss modules in a TypeScript environment, my modules are saved within a property named default. Button-styles.scss .button { background-color: black; } index.tsx import * as React from 'react'; import * as styles from ' ...

Encountering unusual results while utilizing interfaces with overloaded arguments

I came across a situation where TypeScript allows calling a method with the wrong type of argument. Why doesn't the TypeScript compiler flag this as an issue? interface IValue { add(value: IValue): IValue; } class NumberValue implements IValue { ...

Guide to resolving the issue of error Type 'void[] | undefined' cannot be assigned to type 'ReactNode'

I am attempting to map the data Array but I am encountering an error: Type 'void[] | undefined' is not assignable to type 'ReactNode'. Can someone please assist me in identifying what I am doing wrong here? Below is the code snippet: i ...

Passing a callback to a third-party library resulted in an unexpected error

My React+TypeScript code utilizes a component from a third-party library. <ThirdPartyComponent onSelect={(value: any) => {...}} /> The eslint-typescript tool is flagging this as an error: Unexpected any. Specify a different type. eslint(@type ...

What techniques are most effective for creating unit tests in a Node.js environment?

One of the challenges I am facing is writing a unit test for a module where I load a mustache template file. To tackle this, I am exploring the use of mocha, chai, and rewire. Below is an excerpt from my module.js: var winston = require('winston&apo ...

Typescript struggling to load the hefty json file

Currently, I am attempting to load a JSON file within my program. Here's the code snippet that I have used: seed.d.ts: declare module "*.json" { const value: any; export default value; } dataset.ts: import * as data from "./my.json" ...

Implement a click event listener in React.js

How can I implement a callback function for button clicks in my TypeScript code? This is the code snippet: export enum PAYMENT_METHOD { online, offline, } interface Props { paymentMethod: PAYMENT_METHOD; togglePaymentMethod: (paymentMethod: PAYM ...

The functionality of the Drawer component in material-ui v1.0 seems to be incompatible with TypeScript

Every time I try to utilize Drawer from [email protected] using typescript, I encounter the following error: TS2322: Type '{ children: Element; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Re ...

Need to monitor a Firebase table for any updates

How can I ensure my Angular 2 app listens to changes in a Firebase table? I am using Angular2, Firebase, and TypeScript, but the listener is not firing when the database table is updated. I want the listener to always trigger whenever there are updates or ...

Hide the MaterialTopTabNavigator from view

Is there a way to hide the react native MaterialTopTabNavigator on the screen while still maintaining the swiping functionality between screens? I want the user to be able to swipe between screens but not see the tab navigator itself. const Tab = creat ...

Combining namespaces in Typescript declaration files

Currently, I am attempting to combine namespaces from d.ts files. For example, when I attempt to merge namespaces in a single file, everything works as expected. declare namespace tst { export interface info { info1: number; } var a: ...

Exploring various queries in Firestore

Does anyone know if there is a way to create a sentence similar to this one: return this.db.collection('places', ref => ref.where("CodPais", "<>", pais)).valueChanges(); I have tried using != and <> but neither seem to be valid. Is the ...

Serverless-offline is unable to identify the GraphQL handler as a valid function

While attempting to transition my serverless nodejs graphql api to utilize typescript, I encountered an error in which serverless indicated that the graphql handler is not recognized as a function. The following error message was generated: Error: Server ...

Using @HostBinding based on the @Input() condition

I'm attempting to link the CSS class foo to my parent component by utilizing @HostBinding based on a condition I evaluate against a dynamic variable. However, I am struggling to get it to function as expected. Here are the different approaches I hav ...

Next.js routes taking precedence over storybook routes

I recently completed a storybook project. Now, I am looking to integrate it with another project built on next.js. The issue is that Storybook and next.js each have their own set of routes. I want to streamline the routing process by utilizing next.js and ...

Why does the request body show as null even after passing body data in Prisma?

My application uses Prisma for database storage with MySQL. It is built using Next.js and TypeScript. I have set up the API and it is functioning properly. However, when I try to save data sent through the API, the `request.body` is null. Interestingly, wh ...

What is the most effective approach for annotating TypeScript abstract classes that are dynamically loaded?

I am in the process of developing a library that allows for the integration of external implementations, and I am exploring the optimal approach to defining types for these implementations. Illustration abstract class Creature { public abstract makeN ...

Can you clarify the significance of the "1" in this particular Typescript code snippet?

Can anyone provide some insight into the purpose of this '1' in the following TS code snippet? decryptPassPhrase() { this.$encrypt.setPrivateKey(privateKey); this.decryptedPassPhrase = this.$encrypt.decrypt(this.encryptedPassPhrase); ...

The JestImportMeta interface is mistakenly extending the ImportMeta interface, causing an error

While transitioning from jest version 27 to v29, I encountered this issue: node_modules/@jest/environment/build/index.d.ts:329:26 - error TS2430: Interface 'JestImportMeta' improperly extends interface 'ImportMeta'. The types returned ...