Using Jest's moduleNameMapper with Next.js without TypeScript

I've been encountering some challenges trying to implement moduleNameMapper in NextJS using JavaScript. In this particular project, TypeScript is not being utilized.

  • Next: 12.2.5
  • React: 18.2.0
  • Jest: 29.0.1
  • Jest environment jsdom: 29.0.1

Below is the content of my jsconfig.json file

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "@/components/*" : ["components/*"],
            "@/styles/*" : ["styles/*"],
            "@/config/*" : ["config/*"],
            "@/hooks/*" : ["hooks/*"],
            "@/store/*" : ["store/*"],
        }
    }
}

In my project, I am able to do the following imports

import Layout from "@/components/Layout"
import useFetch from "@/hooks/fetch"

However, during testing, I encounter an error message stating

Cannot find module @/hooks/fetch from pages/account/login/index.js

Shown below is my jest.config.js setup

const nextJest = require('next/jest');

const createJestConfig = nextJest({
    dir: "./",
});
const customJestConfig = {
    moduleDirectories: ["node_modules", "<rootDir>"],
    moduleNameMapper: {
        "^@/hooks/*": "/hooks/*"
    },
    testEnvironment: "jest-environment-jsdom",
}
module.exports = createJestConfig(customJestConfig)

Despite my efforts to map the paths in moduleNameMapper, the issue persists. How can I resolve this?

I aim to maintain consistent import formatting for both the project and its tests.

Thank you

Answer №1

Solved the issue by making modifications to the jsconfig.js file

const nextJest = require('next/jest');

const customJestConfig = {
    moduleDirectories: ["node_modules", "<rootDir>"],
    testEnvironment: "jest-environment-jsdom",
};

const createJestConfig = nextJest({
  dir: './',
})(customJestConfig);

module.exports = async () =>
{
  // Generate Next.js jest configuration presets
  const jestConfig = await createJestConfig();

  // Custom `moduleNameMapper` setup
  const moduleNameMapper = {
    ...jestConfig.moduleNameMapper,
    '^@/(.*)$': '<rootDir>/$1',
  };

  return { ...jestConfig, moduleNameMapper };
};

Source: https://github.com/vercel/next.js/issues/36682

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

Control and manage AJAX POST requests in the controller

I'm currently working on implementing an ajax post request feature in my project. The goal is to have a button on my html page trigger a javascript event listener, which then initiates an ajax post request to receive some text data. However, I seem to ...

Steps to update the active state in the "reducer" when clicking on elements outside of the "reducer" area

Working with react-redux has presented some challenges for me. I've created multiple reducers such as action, root reducer, active_step reducer, and list_step reducer. One aspect that I find intriguing is the ability to dynamically map and change the ...

While iterating through a dynamically generated JSON data array, omitting the display of the ID (both title and value) is preferred

I am working with a JSON data Object and using $.each to dynamically retrieve the data. However, I want to display all values except for one which is the ID. How can I achieve this and prevent the ID from being displayed in the HTML structure? Thank you. ...

What could be causing the Material UI tabs to malfunction when dynamically populating the content using a .map function instead of manually inserting it?

I was able to successfully integrate Material UI's tabs by manually adding content, but when I attempted to use a .map function to populate the content from a JSON data source, it stopped working. Can someone help me figure out why? The only change I ...

Looking to display the "loading....." message on a PHP page?

I am working on a PHP webpage where I need to implement the following features: 1. Upon clicking "Say Thanks", it should change to "Done!". 2. Simultaneously, I would like to trigger an action in the indexController. 3. While this action is happening, I wa ...

Does GIF animation operate on the same thread as JavaScript in all popular web browsers?

When my AJAX request is in progress, an animated GIF is displayed to show activity. However, I have noticed that the animation freezes while the response from the request is being processed by a script that heavily updates the DOM. After researching this ...

Uncovering hidden links in a menu with Python Selenium and JavaScript

Can someone provide guidance on how to activate the JavaScript submenu associated with this button, "x-auto-54"? <table id="x-auto-54" class=" x-btn avtar-x-btn x-component x-btn-noicon x-unselectable " cellspacing="0" role="prese ...

Using JQuery to monitor the loading of a newly selected image src attribute

As a newcomer to JavaScript and JQuery, I am facing a challenge that I couldn't find a solution for in other discussions: I have a function that retrieves the path to an image (/API/currentImage) using a GET request and needs to update the src attrib ...

React's struggle with implementing flexbox functionality

Struggling to implement a calculator using React and flexbox, but running into issues with my flexbox layout. I've attempted to troubleshoot using the Chrome Dev Tools but haven't made any progress. import React, { Component } from "react"; imp ...

Press the second form submit button after the completion of another Observable

Below is the unique process we aim to accomplish using solely RXJS Observables: Press Login button (form with username & password). We bind Observable.fromEvent with our form. Upon submitting the form, call loginUser() to send an http request to serv ...

Here's a new take on the topic: "Implementing image change functionality for a specific div in Angular 8 using data from a loop"

I need to create a list with dynamic data using a loop. When I click on any item in the list, I want the image associated with that item to change to a second image (dummyimage.com/300.png/09f/fff) to indicate it's active. This change should persist e ...

Struggling with parsing a JSON object in ReactJS and looking for assistance

Seeking assistance from experts. I am in the process of developing an application that requires parsing every element of a JSON response fetched from an API. Here is the structure of the JSON: const data = [ { "status": 1, "from": "2021-03-09 ...

Rearranging table rows with jQuery based on numerical values within child elements

I require assistance in sorting the rows of a table based on the numbers within certain anchor tags. Below is an example of the table structure: <table id="sortedtable" class="full"> <tbody> <tr> <th>Main tr ...

Why isn't the jQuery click() function functioning on my modified HTML?

I am trying to create a unique version of the go-moku game using different programming languages and databases. My aim is to enhance the game's functionality by incorporating jQuery, PHP, and a MySQL database. var moveCount = -1; setInterval(function ...

Is it possible to remove certain 'css-' class names that MUI automatically applies to its components? (Using Next JS and MUI)

After successfully migrating my create-react-app project to Next JS using the latest version (12.1.0) and following the migration guide at https://nextjs.org/docs/migrating/from-create-react-app, I encountered an unexpected issue. Despite still using MUI a ...

Transfer the layout from one HTML file to multiple others without the need to retype the code

I am working on developing an e-commerce website with HTML/CSS. My goal is to have a consistent template for all product pages that are accessed when clicking on a product. However, I do not want to manually code each page using HTML and CSS. Is there a mo ...

Creating a backup link for a video player component in NextJs

My aim is to make sure that two video player components in a NextJS application can still access and play videos even when the application is running locally using npm run dev without an internet connection. Currently, these two components.. <HoverVi ...

React - Customizable Counter Components - Control All Counters with Parent Component

Hello everyone, I'm fairly new to React and still in the learning process. Currently, I have a challenge that involves creating a simple React Counter app with some specific requirements. The challenge is to build the app without using Redux or hooks. ...

Managing nested Angular repeats with counter

In the previous section of my document, I have a presentation layer that effectively organizes information within a shopping cart. This arrangement functions perfectly fine. At the lower portion, I employ the following code to generate form variables whic ...

Adding a JSON array to HTML using JavaScript

Looking to incorporate JSON Array data into an HTML list with Headings/Subheadings using JavaScript. I experimented with two methods - one involving jQuery and the other mostly vanilla JS. The initial attempt (link here: http://jsfiddle.net/myu3jwcn/6/) b ...