Jest: Test fails due to import statement in node_module dependency

Short Version

I'm experiencing a crash in my Jest test due to a SyntaxError related to an import statement outside a module. The issue arises from a node_module that uses the import statement. How can I resolve this error?

Situation Overview

In developing a Next.js app, I have Jest as my testing framework and employ Magic for authentication purposes. To run my Jest tests in TypeScript, I utilize ts-node.

The specific challenge lies in testing a serverless function that incorporates the @magic-sdk/admin package, which depends on the ethereum-cryptography library for its keccak hash algorithm.

During test execution, it crashes because of the import statement within the ethereum-cryptography package.

 FAIL  src/features/user-authentication/login-handler.test.ts
  ● Test suite failed to run

    Jest encountered an unexpected token
    ...

Test Suites:   1 failed, 1 total
Tests:         0 total
Snapshots:     0 total
Time:          2.292 s
Ran all test suites related to changed files.

My tsconfig.json configuration is as follows:

{
  "compilerOptions": {
    ...
  },
  "exclude": ["node_modules"],
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"]
}

This is how my jest config file (jest.config.ts) looks like:

export default {
  moduleDirectories: ['node_modules', 'src'],
  moduleNameMapper: {
    '\\.(css|less)$': '<rootDir>/src/tests/mocks/style-mock.js',
  },
  setupFilesAfterEnv: ['./jest.setup.ts'],
  setupFiles: ['<rootDir>/src/tests/setup-environment-variables.js'],
};

Attempted Solutions

Despite finding numerous search results for this common error, none of the suggested fixes have worked so far. Here's what I've attempted:

- Including the folder in transformIgnorePatterns did not yield the desired outcome.

- Explicit transformation using transform and ts-jest was also ineffective.

- Changing the module to commonjs in the tsconfig.json file did not address the issue either.

How can I troubleshoot this and successfully execute the test case?

Answer №1

After some troubleshooting, I identified the issue. In my jest.config.ts, I had included src in the moduleDirectories array due to setting up Next.js to handle absolute imports.

  moduleDirectories: ['node_modules', 'src'], // 🔴 wrong

However, once I changed it to explicitly reference from the rootDir, everything started working as expected 👇

export default {
  moduleDirectories: ['node_modules', '<rootDir>/src'],
  moduleNameMapper: {
    '\\.(css|less)$': '<rootDir>/src/tests/mocks/style-mock.js',
  },
  setupFilesAfterEnv: ['./jest.setup.ts'],
  setupFiles: ['<rootDir>/src/tests/setup-environment-variables.js'],
};

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

Next.js is causing an error by not recognizing the document variable

While diving into the world of next.js, I encountered an interesting challenge. In my project, I came across this puzzling error. The culprit seemed to be a module called Typed.js, which threw me off with a peculiar message: Server Error ReferenceError: d ...

Guide on retrieving 'params' in a client-side component within Next13

Is there a way to retrieve query parameters like (/home?id=1) using the useSearchParams hook? I am trying to obtain /home/[id] in a client component, but the old approach of using next/router with router.query is no longer supported in next/navigation. In ...

Is there a way for me to maintain a consistent layout across all pages while also changing the content component based on the URL route in Next.js?

I'm currently working with Typescript and Next.js My goal is to implement a unified <Layout> for all pages on my website. The layout comprises components such as <Header>, <Footer>, <Sidenav>, and <Content>. Here is the ...

Error: Unable to access database due to lock while attempting to deploy Docker Container containing a Next.js application integrated with Drizzle ORM

I'm currently in the process of dockerizing my Next.js application. The tech stack I am using includes Next.js (a Node.js framework), Docker, Drizzle ORM, and better-sqlite3. While it works fine in development without Docker by running pnpm db:gener ...

Subtracted TypeScript concept

Is it possible to create a modified type in Typescript for React components? import {Component, ComponentType} from 'react'; export function connect<S, A>(state: () => S, actions: A){ return function createConnected<P>(componen ...

Having trouble with Angular 2 not properly sending POST requests?

Having some trouble with a POST request using Angular 2 HTTP? Check out the code snippet below: import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import 'rxjs/add ...

I am currently making use of the Material UI accordion component and I would prefer for it to not collapse unless I specifically click on the expandIcon

I have been utilizing the Material UI accordion component and am currently struggling to find a solution that prevents the panel from collapsing when it is clicked. Ideally, I would like to manage the opening and closing of the panel solely through click ...

What is the best way to verify if an object is an instance of a particular class using Jasmine testing?

In the process of developing an Angular application, I am currently working on testing a component using this guide. My goal is to ensure that when my ngOnInit() method is called, it correctly initializes my foos property with an array of Foo objects based ...

Next.js displays an error when attempting to update the `AuthContextProvider` component while rendering the `Login` component

I have developed a basic next.js application that involves user login functionality through a graphql-api. The login process utilizes the react context-API to update the context once the user successfully logs in. Upon successful login, the intention is to ...

Observable<Any> Filter

I am currently utilizing Typescript and Angular 4 in my work. Within my project, I have two lists implemented using rxjs/Rx. ... myList: Observable<MyClass[]>; filteredList: Observable<MyClass[]>; ... My objective is to filter the myList base ...

Apply CSS styling to the shadow root

In my preact project, I am creating a Shadow DOM and injecting a style element into the Shadow root using the following code: import style from "./layout/main.css"; loader(window, defaultConfig, window.document.currentScript, (el, config) => ...

Best method for managing large volumes of images within a NextJS application

Currently, I am working on a NextJS project and I have encountered a situation where I need to save the image path of user profile pictures in the database. I am wondering if it's possible to store these images in the /public/ directory and whether o ...

Unlock TypeScript code suggestions for extended objects

In my app, I use a configuration file named conf.ts to consolidate config values from other files for better organization. By merging these values, it becomes more convenient to access them using Conf.MY_LONG_NAMED_VALUE rather than Conf.SubCategory.MY_LON ...

What is the best way to determine the final letter of a column in a Google Sheet, starting from the first letter and using a set of

My current approach involves generating a single letter, but my code breaks if there is a large amount of data and it exceeds column Z. Here is the working code that will produce a, d: const countData = [1, 2, 3, 4].length; const initialLetter = 'A&a ...

define a variable within a v-for loop

Example of Code <div v-for="item in dataItems"> <div v-if="enableEdit"> <input type="text" v-model="name"> </div> <div v-else> {{name}} </div> <button @click="enableEdit = true">click</button> This ...

Contrast the different characteristics of string dynamic arrays in Angular 6

I am working with two arrays of strings. One array is a dynamic list of checkboxes and the other is the source to check if the item exists in the first array. I need to implement this dynamically using Angular 6, can you help me with this? Currently, the ...

Passing Parent Method to Child Component in React Native

I'm experiencing an issue trying to pass a method from my parent component to a child component. Although I believe my code is correct, I keep getting the error message undefined is not an object(evaluating '_this2.props.updateData'). Despit ...

Utilize PrimeNG's async pipe for lazy loading data efficiently

I have a significant amount of data (400,000 records) that I need to display in a PrimeNG data table. In order to prevent browser crashes, I am looking to implement lazy loading functionality for the table which allows the data to be loaded gradually. The ...

Creating a new TypeScript file via the command line: A step-by-step guide!

When I want to create a new file named main.ts, I try to write the command but it keeps showing an error. "bash: code: command not found" https://i.stack.imgur.com/cpDy3.png ...

I am currently analyzing a JSON file that contains deeply nested JavaScript Objects. My goal is to rearrange the data so that objects containing a specific field value are placed at the top of the list

Currently, I am parsing a JSON file which contains a map of JavaScript objects. For instance: { offers : { "1":{"id":"1", "category":"a", "offerType":"LS"}, "2":{"id":"2", "category":"a", "offerType":"EX"}, ...