Error in Jest Path Mapping: The module named xyz, which is mapped as abc, could not be found

I am having issues using jest (specifically ts-jest) with path mapping. It's failing with the following error:

• Test suite failed to run

    Configuration error:
    
    Could not locate module @app/env.local.json mapped as:
    ./$1.
    
    Please check your configuration for these entries:
    {
      "moduleNameMapper": {
        "/^@app\/(.*)$/": "./$1"
      },
      "resolver": undefined
    }

      13 |
      14 | // Utils / Types / Api
    > 15 | import config from "@app/env.local.json"
         | ^
      16 |
      17 | const URI_TO_DATABASE = "mongodb://localhost:27017/" + config.DATABASE_NAME
      18 |

      at createNoMappedModuleFoundError (node_modules/jest-resolve/build/resolver.js:577:17)
      at Object.<anonymous> (database/database.ts:15:1)

ReferenceError: You are trying to `import` a file after the Jest environment has been torn down. From __tests__/someTest.test.ts.

I believe my jest configuration is set up correctly:

const { pathsToModuleNameMapper } = require("ts-jest/utils")
const { compilerOptions } = require("./tsconfig.json")

module.exports = {
    moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths)
}

And here is my tsconfig settings:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "strict": true,
        "esModuleInterop": true,
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true,
        "resolveJsonModule": true,
        "rootDir": ".",
        "baseUrl": ".",
        "paths": {
            "@app/*": [
                "./*"
            ],
            "@api/*": [
                "api/*"
            ],
            "@database/*": [
                "database/*"
            ],
            "@pdf": [
                "pdf/index.ts"
            ],
            "@assets/*": [
                "assets/*"
            ],
            "@fonts": [
                "assets/fonts/fonts.ts"
            ],
            "@utils": [
                "utils/*"
            ],
            "@dbOperations": [
                "database/dbOperations"
            ]
        }
    },
    "include": [
        "**/*.ts",
        "jest.config.js"
    ],
    "exclude": [
        "node_modules"
    ]
}

I suspect that the error might be related to my project folder structure and ts config.

Currently, it maps @app/* to ./* (as per the error message), which seems correct. However, it's unable to locate the env configuration file.

My project directory looks like this:

|./
|-jest.config.js
|-tsconfig.json
|-moreFiles.ts
|-/database/
|--database.ts <-- imports `@app/env.local.json` and gets called anywhere in chain by jest tests
|-/__tests__/
|--someTest.test.ts
|-env.local.json

Any insights on how to resolve this issue? Your assistance is greatly appreciated, thank you :)

Answer №1

In a recent discussion on Stack Overflow, it was suggested that including

moduleDirectories: ['node_modules', './']
in my jest configuration resolved the issue I was facing. I had to eliminate any imports starting with @app/. Interestingly, all other aliases functioned properly.

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

Why isn't any of my AngularJS code running as expected?

I've recently started learning AngularJS, but I'm encountering an issue where none of my code is being executed when I run the page. Instead, all I see on the website is {{angular-message}} and I'm receiving the error "Error: [ng:areq] Argum ...

How do you activate the background color for paragraphs <p> when a bootstrap button is styled with CSS?

In the code snippet provided below, dynamic creation of paragraphs with changing background colors and styles is demonstrated. One challenge faced in this script is maintaining the printed background colors for each dynamically generated paragraph. The is ...

"Difficulty encountered in getting scroll-x: auto to function properly in iOS and Safari when embedding an image with a click map inside a container

We're encountering an issue with a wide image (a colour palette) that is too large for mobile screens, so we decided to place the image in a container with a horizontal scroll bar. This solution works perfectly on most browsers, but not on iOS and Saf ...

Make sure that JSON.stringify is set to automatically encode the forward slash character as `/`

In my current project, I am developing a service using nodejs to replace an old system written in .NET. This new service exposes a JSON API, and one of the API calls returns a date. In the Microsoft date format for JSON, the timestamp is represented as 159 ...

I'm experiencing some compatibility issues with my script - it seems to be functioning correctly on desktops but not on mobile

Below is a script I've implemented on an html page to toggle the visibility of divs based on user interaction. <script> $(document).ready(function(){ $("#solLink").click(function(){ $(".segSlide").hide(), $(".eduSlide").hide ...

Obtain the jQuery dialog's closure event within the $.Ajax completion function

I have developed a custom jQuery plugin that utilizes jQuery Dialog to showcase messages. Specifically, I am using it within my jQuery $.ajax -->done function. My goal is to capture the close event of the Dialog in the .ajax function so that I can redir ...

The jQuery load() method may not load all elements

I've been struggling with a query issue for quite some time now. I have a Content Management System that I want to integrate into my website, but unfortunately, I am unable to use PHP includes. As an alternative, I decided to utilize jQuery instead. D ...

Creating a TypeScript function that utilizes generics to automatically infer the return type

How can I create a function with a generic argument that can return any type, and have the return type inferred from its usage? I attempted the following code: type Thing<T> = <U>(value: T) => U const shouldMakeStrings: Thing<string> ...

Showing only the objects that are marked as true in the component (React)

I have implemented two key React components. One of them is VideoGameList.js, it serves as an export of an array containing multiple objects. const VideoGameList = [ { id: 1, title: "Fire Emblem Engage", src: vg01, releaseDate: ...

Disabling dates in Kendo Date Time Picker (Angular): An easy guide

<input id="startDate" kendo-date-time-picker k-ng-model="vm.startDate" k-on-change="vm.updateStartDate()" required /> Can someone please explain how to incorporate disabled dates into this date picker without utilizi ...

A helpful guide on passing props to ReactJS components when redirecting

I am facing an issue with passing props while redirecting to a route using React Route (Redirect to). The component (SideBar) is not receiving any props. Can you guide me on how to send and receive props in the component? My requirement is to send a prop f ...

Exploring nested arrays with recursive looping

I have been working on solving this challenge using recursion because I enjoy the challenge. The task at hand involves taking an array of arrays and transforming it into a single array with all the values combined. While I have made good progress, I am e ...

Utilizing OrbitControls with Socket.io in a Three.js Sphere

I'm currently troubleshooting an issue with my project. I have a three.js sphere ("HTML1" on Desktop) with controls (THREE.OrbitControls) that is functioning properly on both my computer and tablet. My goal is to control this sphere through my iPad, s ...

Upon submission of user-entered data, save it in an HTML table by creating an array variable for each column of the table

There is an HTML table containing multiple rows where users can input details such as Sprint, Role, Project, and Comments. The remaining fields, SID and Project Code, are fetched from the backend when the user clicks on the getDetails button. Users have th ...

The issue with the datatable row button functionality is not functioning as expected within the

I am facing an issue with my Jade Template code where I am trying to trigger a JavaScript function when a button is clicked on each row. Despite following the documentation for DataTables and Jade, I am unable to figure out what mistake I am making. It see ...

Take up the full vertical and horizontal space of the elements in each image

Issue: I'm facing a problem with my image slider where I am unable to occupy the full width and height (100%) of the drosp and abc classes. Inquiry: How can I ensure that all images fill their entire space without compromising on quality? code < ...

Pause the counter based on the data attribute containing multiple values

I have a collection of div elements, each with a unique data-attribute value. My goal is to display these values in the divs using JavaScript by incrementing a counter. const numbers = document.querySelectorAll(".number"); console.log(numbers); let c ...

Diving deep into the reasons behind a test's failure

Currently, I am using Postman to test the API that I am developing with express. In this process, I am creating a series of tests. Below is a brief example: tests["Status code is 200"] = responseCode.code === 200; // Verifying the expected board var expe ...

Is it possible for Angular 7 to disconnect from the internet?

I am looking to disable all buttons, clicks, and hyperlinks while displaying a backdrop with the message "GO ONLINE". It may come off as rude, but it is necessary. AppComponent (TS): The connectionMonitor can be used to monitor network connectivity. pr ...

Encountering an error while transmitting variables through ajax

Encountering an issue when attempting to remove a user from the database. Below is the code I have written: On the server side: @RestController public class EmployeeRestController { @DeleteMapping( value = "/delete_user") public List<Em ...