"Troubleshooting: Module not found" (Getting started with Jest in a nested project connected to a shared directory)

I've recently taken over a project that contains the following folder structure:

node_modules/
server/
├── node_modules/
├── src/
│   └── helpers/
│       ├── updateTransactions.ts
│       └── updateTransactions.test.ts
├── jest.config.ts
└── tsconfig.json
shared/
└── helpers/
    └── datetime.ts
src/
└── index.tsx
jest.config.ts
tsconfig.json

When I navigate to the server directory and run yarn test, I encounter the error message:

Cannot find module '../../../shared/helpers/datetime.js' from 'src/helpers/updateTransactions.ts'

This issue seems to be due to Jest not recognizing how to handle the import statement, like

import { getFormattedDatetimeUtcFromBlockTimestamp } from '../../../shared/helpers/datetime.js';
within the updateTransactions.ts file.

It appears to be a simple configuration problem that needs addressing.

Despite attempting various solutions as documented in the commented-out code snippets here, such as:

  • Jest + Typescript + Absolute paths (baseUrl) gives error: Cannot find module
  • Jest gives `Cannot find module` when importing components with absolute paths
  • Jest "Cannot find module" with typescript paths in CI
  • Problem mapping path in ts-jest (TypeScript Jest), module cannot be found

Answer №1

The key factor that contributed to its success was modifying my jest.config.ts:

// https://example.github.io/ts-jest/docs/guides/esm-support/

/* eslint-disable canonical/filename-match-exported */
import { type JestConfigWithTsJest } from 'ts-jest';

const jestConfiguration: JestConfigWithTsJest = {
  // [...]
  preset: 'ts-jest/presets/default-esm', // or other ESM presets
  moduleNameMapper: {
    '^(\\.{1,2}/.*)\\.js$': '$1',
  },
  transform: {
    // '^.+\\.[tj]sx?$' to process js/ts with `ts-jest`
    // '^.+\\.m?[tj]sx?$' to process js/ts/mjs/mts with `ts-jest`
    '^.+\\.tsx?$': [
      'ts-jest',
      {
        useESM: true,
      },
    ],
  },
};

export default jestConfiguration;

Refer to the documentation here:

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

Is there a way to determine the quantity of lines within a div using a Vue3 watcher?

Is it feasible to determine the number of text lines in a div without line breaks? I am looking to dynamically display or hide my CTA link based on whether the text is less than or equal to the -webkit-line-clamp value: SCRIPT: const isExpanded = ref(true ...

Vue3 with Typescript may either display an error message or remain empty when handling props

I've been attempting to utilize the default Quasar card component in order to display data received from props. Unfortunately, I haven't had any success as my component remains empty and I keep encountering various errors with each attempt. Rece ...

What purpose does a private property serve within the interface?

Given the following code snippet: class X { bar() { return "bar" } constructor(private readonly x: number){} } interface Y extends X { } const f = (y: Y) => { console.log(y.bar()); } f({ bar: () => "tavern"}); The code does ...

Tips for emulating a file upload in Jest

I am currently working on writing a test in jest to carefully analyze the functionality of my reactJS components. In order to validate my reactjs component, I am looking for a way to simulate a file upload within jest. Could anyone provide guidance on how ...

Tips for toggling visibility in Angular 2

I utilized [hidden] in the following way where the value of "secondTab" is set to true. <form #siteForm="ngForm" novalidate (ngSubmit)="saveSite(siteForm.value,siteForm.valid)" class="admin-modal"> <div class="txt-danger">{{errorMessage}}&l ...

Utilizing Typescript's type inference within a universal "promisify" function

Unique Context Not long ago, I found myself delving into the world of "promisification" while working on a third-party library. This library was packed with NodeJS async functions that followed the callback pattern. These functions had signatures similar ...

Uncovering TypeScript's Type Inference Power Through the keyof Keyword

Recently, I encountered a situation where I needed to utilize an abstract class. export abstract class ABaseModel { public static isKeyOf<T>(propName: (keyof T)): string { return propName; } } Following that, I also created another class wh ...

What is the reason behind tsc (Typescript Compiler) disregarding RxJS imports?

I have successfully set up my Angular2 project using JSPM and SystemJS. I am attempting to import RxJS and a few operators in my boot.ts file, but for some reason, my import is not being transpiled into the final boot.js output. // boot.ts import {Observa ...

Show a notification pop-up when a observable encounters an error in an IONIC 3 app connected to an ASP.NET

Currently, I am in the process of developing an IONIC 3 application that consumes Asp.NET web API services. For authentication purposes, I have implemented Token based auth. When a user enters valid credentials, they receive a token which is then stored in ...

Best practices for utilizing forwardRef and next/dynamic in next.js version 13.4 with the "react-email-editor" component

I've been attempting to utilize the "react-email-editor" library in a Next.js project. My goal is to copy the email content generated within the editor to the clipboard. Since the library relies on browser interaction and the use of the "window" objec ...

The specified column `EventChart.åå` is not found within the existing database

I've been developing a dashboard application using Prisma, Next.js, and supabase. Recently, I encountered an issue when making a GET request. Prisma throws an error mentioning a column EventChart.åå, with a strange alphabet "åå" that I haven&apos ...

What is the syntax for creating a zip function in TypeScript?

If I am looking to create a zip function: function zip(arrays){ // assume more than 1 array is given and all arrays // share the same length const len = arrays[0].length; const toReturn = new Array(len); for (let i = 0; i < len; i+ ...

Visual Studio Code unable to locate source maps for typescript debugging

Looking for some help debugging a basic Hello World TypeScript file. Whenever I try to set a breakpoint, it seems like VS Code is having trouble locating the source map, even though it's saved in the same directory. I'm using Chrome as my browser ...

What strategies can I implement to streamline the use of these functions instead of creating a separate one for each textfield

Currently, I am learning how to use spfx with SPO (SharePoint Online). In my form, there are multiple text fields that need to be handled. I have two class components named A and B. Whenever a textfield in component B is typed into, a function sends the in ...

Utilize the identical element

Incorporating the JwPaginationComponent into both my auction.component and auctiongroup.component has become a necessity. To achieve this, I have created a shared.module.ts: import { NgModule } from '@angular/core'; import { JwPaginationCompon ...

TypeScript async function that returns a Promise using jQuery

Currently, I am facing a challenge in building an MVC controller in TypeScript as I am struggling to make my async method return a deferred promise. Here is the signature of my function: static async GetMatches(input: string, loc?: LatLng):JQueryPromise& ...

Creating a Modal using Typescript with NextJS

Currently, I'm working on creating a modal within my app using NextJS with Typescript. Unfortunately, I've been struggling to eliminate the warning associated with my modal selector. Can someone provide guidance on how to properly type this? cons ...

The seamless fusion of Express with Typescript

Hello and thank you for taking the time to assist me. I recently completed a Cron app using Node.JS. I wanted to add a website hosted by the Node.js server with Express. I developed this TypeScript website in a separate folder, but encountered errors when ...

Creating an interface that accurately infers the correct type based on the context

I have an example below of what I aim to achieve. My goal is to start with an empty list of DbTransactInput and then add objects to the array. I experimented with mapped types to ensure that the "Items" in the "Put" property infer the correct data type, w ...

Achieving a delayed refetch in React-Query following a POST请求

Two requests, POST and GET, need to work together. The POST request creates data, and once that data is created, the GET request fetches it to display somewhere. The component imports these hooks: const { mutate: postTrigger } = usePostTrigger(); cons ...