Unable to locate module using absolute import in a Next.js + TypeScript + Jest setup

Currently in my NextJS project, I am utilizing absolute imports and testing a component with Context Provider. The setup follows the instructions provided in this jest setup guide

TEST:

import { render, screen } from 'test-util';

import { Sidebar } from '@/components/Sidebar/Sidebar';
  test('Ensuring the presence of a brand image', () => {
    render(<Sidebar />);
    const brandLogo = screen.getByAltText('logo');
    expect(brandLogo).toBeInTheDocument();
  });

Below is my test-util.tsx located in the root folder.

import React, { FC, ReactElement, ReactNode } from 'react';
import { render, RenderOptions } from '@testing-library/react';
import { AuthProvider } from 'store/auth';

const AllTheProviders: FC = ({ children }) => {
  return <AuthProvider>{children}</AuthProvider>;
};

const customRender = (ui: ReactElement, options?: Omit<RenderOptions, 'wrapper'>) =>
  render(ui, { wrapper: AllTheProviders, ...options });

export * from '@testing-library/react';
export { customRender as render };

This is my jest.config.js located in the root directory.

// @ts-nocheck
const nextJest = require('next/jest');

const createJestConfig = nextJest({
  // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
  dir: './',
});

// Additional configuration to be passed to Jest
const customJestConfig = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  moduleNameMapper: {
    '^@/components/(.*)$': '<rootDir>/components/$1',
    '^@/pages/(.*)$': '<rootDir>/pages/$1',
    '^@/firebase/(.*)$': '<rootDir>/firebase/$1',
    '^@/store/(.*)$': '<rootDir>/store/$1',
  },
  testEnvironment: 'jest-environment-jsdom',
};

// Exported this way to enable next/jest loading the Next.js config which is asynchronous
module.exports = createJestConfig(customJestConfig);

This is jest.setup.js within the root folder.

import '@testing-library/jest-dom/extend-expect';

The encountered error:


 FAIL  components/Sidebar/__test__/Sidebar.test.tsx
  ● Test suite failed to run

      Cannot find module 'test-util' from 'components/Sidebar/__test__/Sidebar.test.tsx'

        1 | import { Sidebar } from '@/components/Sidebar/Sidebar';
      > 2 | import { render } from 'test-util';
          |                                   ^
        3 |

Here is tsconfig.paths.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/pages/*": ["./pages/*"],
      "@/components/*": ["./components/*"],
      "@/features/*": ["./features/*"],
      "@/firebase/*": ["./firebase/*"],
      "@/store/*": ["./store/*"]
    }
  }
}

To overcome this issue, I aim to use

import { render, screen } from 'test-util';

A valid alternative approach that works for me is:

import { render, screen } from '../../../test-util';

import { Sidebar } from '@/components/Sidebar/Sidebar';
  test('Ensuring the presence of a brand image', () => {
    render(<Sidebar />);
    const brandLogo = screen.getByAltText('logo');
    expect(brandLogo).toBeInTheDocument();
  });

Answer №1

My setup is somewhat similar, and it's been effective for my needs.

You might want to consider including

moduleDirectories: ["node_modules", "<rootDir>/"]
within the customJestConfig object.

Answer №2

I encountered a comparable issue and

moduleDirectories: ['node_modules', '<rootDir>/src'],

using customJestConfig resolved the problem for me

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

Having trouble getting the Bootstrap modal form to submit when using Knockout's submit binding?

Check out my jsFiddle example by clicking here. I am currently working on a form within a bootstrap modal. The problem I'm facing is that the knockout submit binding doesn't get executed unless the user clicks on the submit input. It seems like ...

Utilizing the power of Koa.js in conjunction with MongoDb for seamless development

Having an issue, or maybe just lacking some knowledge here. The question is pretty straightforward - I have this code: router.get('/', (ctx, next) => { MongoClient.connect(url, {useNewUrlParser: true}, function (err, db) { if (err) th ...

Setting up a div as a canvas in Three.js: Step-by-step guide

Is there a way to adjust the JavaScript in this three.js canvas example so that the scene can be contained within a specific div element on a webpage? Here is the example: https://codepen.io/PedalsUp/pen/qBqvvzR I would like to use this as the background ...

Retrieve user details from a NextJS application following a successful Keycloak authentication on a Kubernetes cluster

I've been attempting to retrieve the authenticated user information in my NextJS app after being redirected to it following a successful Keycloak login on a different tab located at localhost:8080/auth. The ingress (entry point) is responsible for ch ...

What could be causing the input field state to remain static even as I type in the MUI textField?

In my React.js component, I am facing an issue where the textField is not updating when I try to type anything. Upon debugging, I discovered that when the first character is entered, the component re-renders and loses its previous state, causing the textF ...

show a notification once the maximum number of checkboxes has been selected

I came across this code snippet from a previous question and I'm interested in making some modifications to it so that a message can be displayed after the limit is reached. Would adding a slideToggle to the .checkboxmsg within the function be the mos ...

Node.js with PostgreSQL (pg): The client connection has already been established. Reusing the client is not allowed

Currently, I am working on creating a basic register/login system and I'm facing an issue with checking for existing usernames. Here are the steps I've followed: Visit the localhost:3000/users/register page Input all required details and click o ...

Emphasize the center row within a moving table

I am interested in developing a scrolling table where only 10 rows are visible at any given time, with the middle row set to stand out even during scrolling. The concept is that as the user scrolls down, the highlighted row changes progressively as they c ...

Console frozen when executing an async JavaScript script to populate a Mongoose database

I'm currently delving into a personal project and aiming to unravel the intricate logic that is preventing my Node JS process from closing after executing populateTransactions(). My assumption is that the issue lies in not properly closing the DB con ...

Replacing text with new content when text is stored in a separate file

After organizing all the strings from my code, I compiled them into a file named constants.ts. export class Constants { public static API_URL = '/api/'; public static CREATE_CHILD_API_URL = Constants.API_URL + '%s' + '/create- ...

Is there a way to confirm the presence of multiple attributes in a JSON format using JavaScript?

Currently, I am developing a module that processes multiple complex JSON files and requires a method to notify users if certain elements are missing. Although the current approach works, I can't shake the feeling that there must be a more efficient a ...

AngularJS: How to automatically scroll to the bottom of a div

I cannot seem to scroll to the last message in my chat window. var app=angular.module('myApp', ['ngMaterial'] ); app.controller('ChatCtrl', function($window, $anchorScroll){ var self = this; self.messageWindowHeight = p ...

The program encountered an error stating: "require variable not found at"

I am facing an issue while using jasmine with Grunt. Every time I run my jasmine tests, I encounter the following error: ReferenceError: Can't find variable: require at In my Gruntfile.js, this is how I have configured jasmine: jasmine: { js: ...

Looking to transition from Node.js version v4.4.5 to v6.11.0 on your Windows system?

npm cache clean npm update -g I attempted upgrading using the provided commands, but unfortunately, the update did not go through as expected. Seeking advice for a successful update process. (Currently on Node.js 4.4.5 and aiming to upgrade to Node.js 6. ...

Enhance your user interface by adding a tooltip above a button

I am currently working on creating a button that can copy content from a variable into the clipboard using TypeScript and Material-UI. Here is what I have tried: const [copySuccess, setCopySuccess] = useState(''); const copyToClipBoard = async ( ...

How does a browser automatically fill in email and password fields?

When using a text input and a password input in my single page app, Chrome often prompts to remember the information for autofill. However, I am encountering an issue where it doesn't actually autofill the information. Does anyone know how to trouble ...

Endlessly triggering document.execCommand, the JavaScript selectionchange-EventListener seems to have a mind of

I recently implemented an event listener for selectionchange in the following manner: document.addEventListener("selectionchange", function() { highlight(); console.log("selectionchange-triggered"); }, false); After that, I included the code bel ...

Perform validation on input by monitoring checkbox changes in Angular 4

I am currently working on a project where I need to loop through an array of key values in order to create a list of checkboxes, each accompanied by a disabled input field as a sibling. The requirement is that upon checking a checkbox, the corresponding in ...

Is it possible to manipulate an Angular #variableName in order to retrieve an ElementRef for an HTML element?

Suppose I have a scenario where I create a button like this: <button #myButton>My Button</button> ...and then use ViewChild in the following way: @ViewChild('myButton', { static: true }) createButton: ElementRef; In this case, creat ...

Windows location does not change after an XMLHttpRequest is made

Here is my code that uses XMLHttpRequest: function SignUp() { signUpConnection = new XMLHttpRequest(); signUpConnection.onreadystatechange = processRegistration; signUpConnection.open('GET', 'index.php?registrarse=&username= ...