Cannot locate module in Jest configuration

I'm struggling to understand config files and encountering issues while attempting to run jest unit tests:

 Cannot locate module '@/app/utils/regex' from 'src/_components/DriverSearchForm.tsx'

Here's my jest configuration:

    import type { Config } from 'jest'
import nextJest from 'next/jest.js'

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

const config: Config = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
  moduleDirectories: ['node_modules', '<rootDir>/src'],
  moduleNameMapper: {
    '^@/_components/(.*)': '<rootDir>/src/_components/$1',
  },
  testEnvironment: 'jsdom',
  preset: 'ts-jest',
  transform: {
    '^.+\\.(js|jsx|ts|tsx|mjs)$': ['ts-jest', { tsconfig: 'tsconfig.test.json' }],
  },
}

export default createJestConfig(config)

Answer №1

In this setup, the key serves as the alias for the module name, while the value represents the target module to map to. For instance, when you import from @/app/utils/regex, it will be directed to the <rootDir>/app/utils/regex module.

<rootDir>/jest.config.js:

moduleNameMapper: {
    '^@/app/(.*)': '<rootDir>/app/$1',
}

<rootDir>/tsconfig.json:

"paths": {
  "@/app/*": [
    "app/*"
  ]
}

<rootDir>/app/utils/regex.ts
:

export const regex = /test/i

index.ts:

import { regex } from '@/app/utils/regex';

console.log(regex);

index.test.ts:

import './';

describe('78224123', () => {
  test('should pass', () => {
    expect(1 + 1).toEqual(2);
  });
});

Output of the test:

  console.log
    /test/i

      at Object.log (stackoverflow/78224123/index.ts:3:9)

 PASS  stackoverflow/78224123/index.test.ts (7.62 s)
  78224123
    √ should pass (2 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        18.59 s

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

What is the process for unsubscribing through an HTTP post request within an Angular application

There is a POST API set up through API Gateway on AWS, but it seems to be returning an infinite loop of arrays, as shown in the image below. How can I make it return just one array? Multiple requests Below is the code snippet: Angular import { Componen ...

Creating and troubleshooting an Angular 7 project in Visual Studio 2017

After setting up my angular7 project with the ng new my-app command (following the steps at https://angular.io/guide/setup-local), I wanted to continue developing and debugging using Visual Studio 2017 (not Visual Studio Code). When attempting to use Visu ...

Introducing a delay in an observable causes incomplete data to be received in Angular using rxjs

Currently, I am facing an issue in my code where I am trying to introduce a delay using timer(500). However, the problem is that it is only returning partial data. Instead of the expected 17 fields, it is only returning 2 fields. Below is my code snippet f ...

Closing a modal from a nested modal sub-component

I am facing a query regarding how to close a Modal from within a sub-component of the same Modal itself. Allow me to elaborate on what I am trying to achieve here. I have developed a Modal that is triggered from a Component to enable users to add a new Cl ...

Dealing with errors when making an API call within the getStaticProps method in NextJS

How can I handle errors for each individual API call in the getStaticProps function? export async function getStaticProps(context) { const fund = context.params.fund; try { const avggReturnsRes = await fetch( https://localhost:8000/avggaut ...

Exploring the Usage of Jasmine Testing for Subscribing to Observable Service in Angular's OnInit

Currently, I am facing challenges testing a component that contains a subscription within the ngOnInit method. While everything runs smoothly in the actual application environment, testing fails because the subscription object is not accessible. I have att ...

Erase Typescript Service

To remove a PostOffice from the array based on its ID, you can use a checkbox to select the desired element and then utilize its ID for the delete function. Here is an example: let postOffices = [ {postOfficeID: 15, postCode: '3006&ap ...

Removing data based on various criteria in Prisma

While I understand that the where clause in Prisma requires a unique input for its delete operation, I have utilized the @@unique function to ensure that multiple conditions need to be columns together and must be unique. However, I am struggling with how ...

Tips for simulating a configuration dependency using Proxyquire in TypeScript

Within my codebase, there exists a config.ts file that contains the following method: // Config interface is utilized to specify expected values export default function getConfig(): Config { return {amount: 50} } In a specific class located at ../src ...

What is the most effective way to transfer visitor hits information from an Express.js server to Next.js?

I've developed a basic next.js application with an express.js backend. What I'm aiming for is to have the server track hits every time a user visits the site and then send this hit count back to the next.js application. Check out my server.js cod ...

Remove user from axios response interceptor for server-side component

In my Next.js 14 application, I have set up axios interceptors to handle errors. However, I need assistance in logging out the user and redirecting them to the '/login' page if any error occurs. Below is the code snippet for the interceptors: axi ...

Typescript library available as a private npm dependency

I have developed a Typescript library that I bundle as an npm module. During the development of my frontend application, I easily integrated this library using yarn link. As I set up GitLab CI for other developers to work on the frontend application, I am ...

Is it possible for TypeScript to convert a generic enum type into a string at runtime?

Enumerations and interfaces are an important part of my codebase: enum EventId { FOO = 'FOO', BAR = 'BAR', } interface EventIdOptionsMap { [EventId.FOO]: { fooOption: string; }, [EventId.BAR]: { barOption: number; } ...

Enhance Summernote functionality by creating a custom button that can access and utilize

Using summernote in my Angular project, I am looking to create a custom button that can pass a list as a parameter. I want to have something like 'testBtn': this.customButton(context, listHit) in my custom button function, but I am unsure how to ...

Aligning Description Item components horizontally in antdLearn how to easily horizontally align Description

Currently, I am utilizing the `antd` Description components. In this scenario, when there is no `title` for the items, the value should be aligned to the left. You can see an example of this alignment in the image below: https://i.sstatic.net/Ah70f.png I ...

Angular2 Navigation: Redirecting to a dynamically constructed route

To start, I need to automatically redirect to today's date as the default. Below is the routing configuration I currently have set up: import { CALENDAR_ROUTE } from './_methods/utils'; export const appRoutes: Routes = [ { path: Cal ...

Encountering an unexpected token error in Vercel during deployment, even though the code runs smoothly in the

I'm facing an issue with a SyntaxError: Unexpected token '??='. I am not sure how to resolve it, so any help would be greatly appreciated. Thank you in advance. SyntaxError: Unexpected token '??=' at wrapSafe (internal/modules ...

What is the best way to halt the parcel/babel/typescript process when encountering compilation errors or warnings?

index.jsx import React from 'react' import ReactDOM from 'react-dom' import Home from "./home"; const x:number = "aaa" const x:number = "aaa" const x:number = "aaa" ReactDOM.render(<Home/>, document.getElementById('root&ap ...

Issue with MathJax rendering within an Angular5 Div that's being observed

I am trying to figure out how to enable MathJax to convert TeX to HTML for elements nested within my div. Here is the current content of app.component.html: <p> When \(a \ne\) It works baby </p> <div class="topnav"> ...

Facing problem with Angular 7 when making a GET request for non-JSON data

Currently, I am retrieving JSON data from a URL using the following method: this.http.get('http://localhost:3200/mydata').subscribe(data => { console.log(data); }); The response is in JSON format, and everything seems to be working fine. ...