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

Save the function as a local variable and preserve the reference to the current object

In the prototype of my Car object, I have a function that looks like this: Car.prototype.drive = function() { this.currentSpeed = this.speed; } I find myself needing to call this drive function frequently within another function of the Car prototype. ...

What is the best way to integrate GTM with the NextJS Script component?

Exploring the script component within NextJS has opened up new possibilities (https://nextjs.org/docs/basic-features/script) I am curious about whether Google Tag Manager can be integrated using this feature. ...

Exploring the principles of object-oriented design within the context of Node

I am facing challenges with the asynchronous flow of Node.js. Let's assume we have the following class: function myClass() { var property = 'something'; var hasConnected = false; this.connect = function(params) { // Logic to conn ...

Creating a registration and authentication system using firebase

When using Google authentication with Firebase, is the Signup and Login logic the same? I am creating a page for user authentication but I'm unsure if I should have separate pages for signing up and logging in. This confusion arises from the fact that ...

What are some tips for incorporating vue.js into a basic web application?

I've been trying to incorporate vue.js into my web application, but for some reason, it's not loading and the HTML is not firing in the browser. Please take a look at the code snippet below: <!DOCTYPE html> <html> < ...

Verifying that the data has been successfully saved using JavaScript

When a user submits a small chunk of data via AJAX using a standard update action and a remote form, the information is sent to the action as javascript. The response is then rendered in javascript utilizing format.js. def update @message = Message.wher ...

What is the best method to securely install a private Git repository using Yarn, utilizing access tokens without the need to hardcode them

My initial thought was to utilize .npmrc for v1 or .yarnrc.yml for v2/3/4, but in all scenarios, Yarn does not even attempt to authenticate with Github. nodeLinker: node-modules npmScopes: packagescope: npmAlwaysAuth: true npmAuthToken: my_perso ...

When a function is called, retrieve a specific number of elements from an array using the slice method in

If I have an array of 15 objects, but I am only displaying 5 on the browser using this code: const displayedArray = array.slice(0,4) I also have a function that will load another 5 objects each time a user scrolls down. displayedArray.concat(array.slice ...

Why is the body the last element in Angular modules arrays?

I have a question regarding architectural practices. When defining an Angular module, one common approach is to do it like this: angular.module('app', []) .controller('Ctrl', ['$scope', function Ctrl($scope) { //body.. ...

Utilizing Unix timestamps for x-values while displaying dates as x-labels in an ECharts line chart

I'm struggling with incorporating date-converted unix timestamps as values in my ECharts graph. The x-axis of my chart is meant to display the recording time for each buy or sell price, represented by respective lines. Everything functions properly wh ...

Implementation of the I18next library

I am currently integrating react-i18next into my application to implement a switch button for French and English languages. Unfortunately, I am facing some issues as the translation is not working properly. I suspect it's related to the JSON file reco ...

"Is there a way to modify the color of the button once it's been clicked, but only for the specific button that was

Looking to create a Quiz App using React and facing an issue where all buttons change color when clicked, instead of just the one that was clicked. Any solutions on how to make only the clicked button change its color in React.js? App.js import Main from ...

Optimize my webpage for a specific location

While developing a game website, I am interested in learning how to enable only specific parts of my website to function while disabling the rest. How can this be achieved? ...

Implementing stop loss with node-binance-api: A step-by-step guide

Currently utilizing node-binance-api for trading purposes. I have initiated an order by executing the following lines of code: let adjustLeverage = await binance.futuresLeverage(coin, 2); let res_2 = await binance.futuresMarketSell(coin, quantity); . Subs ...

Ways to ascertain if a view has completed rendering in JavaScript

I am currently building my application using the awesome backbone.js framework. Within my code, I have this layoutView that handles rendering the overall layout and also includes a smaller profile section. The dilemma I'm facing is with the timing o ...

Trouble reading property 'map' in a react-redux todo application

Greetings! I am currently in the process of developing a to-do list application, but I have encountered the following error: TypeError: Cannot read property 'map' of undefined Below is the code snippet where the error occurs: 4 | function T ...

Encountering a build error with private identifiers while implementing the openai 4.0 package in next.js version 13

After incorporating the new 4.0 openai package into my next.js app, I encountered an error during the build process when using it solely on the server side. - info Linting and checking validity of types .Failed to compile. ./node_modules/openai/src/core.t ...

My Angular Router is creating duplicate instances of my route components

I have captured screenshots of the application: https://ibb.co/NmnSPNr and https://ibb.co/C0nwG4D info.component.ts / The Info component is a child component of the Item component, displayed when a specific link is routed to. export class InfoComponent imp ...

If you include react-multi-date-picker with the render prop set to <InputIcon />, it may trigger a warning in

Looks like the code is missing a function with that name. I followed the documentation and added the icon, but ended up receiving a warning. In next-dev.js:20 Warning: React is not recognizing the handleValueChange prop on a DOM element. To avoid this wa ...

How can I retrieve data ordered by a specific field in a related table using Prisma?

I'm currently diving into the world of Prisma, but I've hit a roadblock with a seemingly straightforward issue. Imagine having these simplified entities: model User { id Int @id @default(autoincrement()) email String ...