The module '#node-web-compat' seems to be missing in the aws-jwt-verify library during testing in Next.js

Problem description

When testing a service in an API used in a Next.js app and using Babel Jest for specific test files, I'm encountering an issue regarding locating a module. The error that appears in the terminal is shown below.


      Cannot find module '#node-web-compat' from 'node_modules/aws-jwt-verify/dist/cjs/https.js'

      Require stack:
        node_modules/aws-jwt-verify/dist/cjs/https.js
        node_modules/aws-jwt-verify/dist/cjs/jwk.js
        node_modules/aws-jwt-verify/dist/cjs/jwt-rsa.js
        node_modules/aws-jwt-verify/dist/cjs/index.js
        pages/api/auth/auth.service.ts
        __tests__/sign-up/api/auth/auth-service.test.ts

        at Resolver._throwModNotFoundError (node_modules/jest-resolve/build/resolver.js:491:11)
        at Object.<anonymous> (node_modules/aws-jwt-verify/dist/cjs/https.js:9:28)
  

The service being tested is utilized by TypeScript decorator in middleware. It functions correctly during manual testing but encounters issues only when running tests.

Objective

The goal is to unit test a service that utilizes the library aws-jwt-verify to verify JWT access tokens. The aim is to mock it and use it in Jest unit tests.

Tried methods

I attempted copying the dependency to devDependencies and reinstalling packages, but this did not resolve the issue.

Dependencies in package.json

{
    ...
    "dependencies": {
      "@aws-sdk/client-cognito-identity-provider": "^3.137.0",
      "@chakra-ui/react": "^2.2.3",
      ...
    }
    ...
  }
  

tsconfig.json

{
    "compilerOptions": {
      "target": "es5",
      ...
    },
    ...
  }
  

jest.config.js


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

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

    const customJestConfig = {
      moduleDirectories: ['node_modules', '<rootDir>/']
    };

    module.exports = createJestConfig(customJestConfig);
  

auth.service.ts


    // Code for auth.service.ts goes here
  

auth-service.test.ts


    // Code for auth-service.test.ts goes here
  

Answer №1

I recently encountered a similar issue while working with TypeScript, Jest, and ts-jest. Fortunately, I was able to find the solution in a GitHub thread. https://github.com/facebook/jest/issues/12620

To resolve the issue, I simply had to include the following configuration in my jest.config file:

  moduleNameMapper: {
    '#node-web-compat': "./node-web-compat-node.js",
  }

Answer №2

Challenge encountered with mocking library After attempting to revert back to version 2.1.3 of the library, it made a difference in resolving the issue. I found guidance from this source

Difficulty faced with mocking functionality I opted to utilize spyOn

import { CognitoJwtVerifier } from 'aws-jwt-verify';
...
jest.mock('aws-jwt-verify');

test('my test', () => {
 jest.spyOn(CognitoJwtVerifier, 'create').mockImplementation(() => {
   return {
     verify: jest.fn().mockResolvedValue({
     exp: Math.floor(Date.now() / 1000) + 3600,
     client_id: process.env.COGNITO_WEB_CLIENT_ID,
     iss: `https://cognito-idp.${process.env.AWS_REGION}.amazonaws.com/${process.env.COGNITO_USER_POOL_ID}`,
     token_use: 'access'
       })
     };
  });
})

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

Learn how to easily send a collection of images to Cloudinary by utilizing Axios and React hook form within a Next.js environment

In the code snippet provided, there seems to be an issue where only a single image is uploaded to the Cloudinary API even though multiple images are specified in the input tag. The frontend logic loops through the event target files and appends them to for ...

The initial function that gets executed in the lodash chain is tap()

When using lodash chain to perform actions synchronously, I encountered an issue where .tap() is executed before the desired stage. I have been unable to find a solution using promises. I expected lodash chain to ensure actions are carried out in a synch ...

After upgrading from Next.js 14.1.0 to 14.1.4, I encountered an error stating that the session cookie exceeds the allowed 4096 bytes limit in Next Auth

I recently updated my NextJs frontend to version 14.1.4 and encountered an authentication API error when using Next-Auth with Express as the backend. Reverting back to the previous version (14.1.0) resolved the error, but now I am facing a new issue while ...

Version 4.0 of Electron-React-Boilerplate has encountered an error: The property 'electron' is not recognized on the type 'Window & typeof globalThis'. Perhaps you meant to use 'Electron' instead?

I encountered an error while attempting to call the IPCrenderer using the built-in context bridge. The error message reads as follows: Property 'electron' does not exist on type 'Window & typeof globalThis'. Did you mean 'Elect ...

How can I resolve the Error: Element type is invalid?

https://i.sstatic.net/9PehR.jpgI am encountering the error message displayed above, and I am uncertain about the cause of this issue. In the code snippet below, I am fetching data from a file named Data.js located in my root folder. When I run the app, I r ...

A Step-by-Step Guide on Including TypeScript Definitions in .NET Core Nuget Packages

Our internal NuGet Package includes both .NET Code and a TypeScript Definition File (*.d.ts). Here is what the package contains: https://i.sstatic.net/7vRxx.png Upon installation of the package into a new .NET Core project, the solution explorer displays ...

Is there a method to authenticate the request sent to an API and confirm the response upon clicking a page element?

Is it viable to confirm the correct request being sent and receive the accurate response from the API in a Node.js+Protractor environment during UI testing when clicking a button? ...

Displaying a horizontal scroll bar for legends in ECharts can be achieved by limiting the legend to three lines. If the legend items exceed this limit, they will scroll horizontally to accommodate all items

I am currently utilizing ECharts to display trend data in a line chart format. With 50 different series to showcase, each series comes with its own legend. My objective is to arrange the legends at the top of the chart, while limiting them to a maximum of ...

Is there a way to retrieve the name of a document stored within a collection using Firebase Firestore and Firebase Storage

When fetching data from the 'users' collection in Firebase Firestore and mapping the response, I have a function that converts the array of domains and filters out any domains that do not meet certain criteria. Here's an example: Sample dom ...

Incorporating a YouTube channel onto a website with React and Typescript, only to be greeted with a

After executing the following code snippet, everything runs smoothly, except for the YouTube player displaying a 404 error. I suspect that there might be an issue with the embedded URL. In the code below, I define a constant called YouTubePlayer which lo ...

Tips on retrieving filtered data from the datasource using the isAllselected function, specifically in the checkbox list function "isAllSelected" within Angular 7

I am currently working with a mat table that has checkboxes for selecting all/row items and a filter function. When I apply a filter to the data source, I want to retrieve all the filtered data from this source. After correctly applying the filter, I can ...

Encountering an issue while trying to execute the getServerSideProps function within _app.js in Next

I'm looking to gain a better understanding of how to utilize a specific function for retrieving session information and where would be the best placement for my Navigation component. Currently, I have my navigation bar nested within the _app.js file ...

What is the functionality of input onChange in React when using state management?

Whenever I try to log the value of the input after each onChange event, there seems to be an odd one event delay. For example, if 'some text' is the default input value and I remove the letter 't' by pressing backspace/delete, it first ...

Error suddenly appeared when trying to serve a previously functional project locally: Firebase function module not found

After not making any changes to my firebase-related files, I suddenly started encountering the following issue that I just can't seem to figure out: We were unable to load your functions code. (see above) - It appears your code is written in Types ...

Drawing coordinate lines on a two-dimensional array that simulates a grid

Are you solving a challenging code problem from the advent of code series? Check out the problem description here. The task involves processing input data in the form of coordinate lines on a grid (x1,y1 -> x2,y2). The goal is to populate a 2D array wi ...

When trying to update a variable within the then() method of a Promise, the variable does not reflect

While the console.log inside the for loop successfully prints project with the correct updated attributes for both role and user within the proposer object, it seems that once outside of the loop, the changes are not retained. At that point, all I see is ...

The type '(params: any) => CSSProperties' does not share any properties with the type 'Properties<string | number>'. Perhaps you meant to invoke it?

Why isn't this property working in react CSS when it is of type CSSProperties? How can I make it work with Properties<string | number>? export const fields: GridFieldsConfiguration[] = [ { ...defaultColDefs, field: &a ...

Utilizing the spread operator in Typescript interfaces: best practices

I have a react component that includes the spread operator operating on ...other and passed down to lower levels of the component. interface ButtonProps { colourMode: string; regular: boolean; buttonText: string; disabled?: boolean; iconSize?: st ...

Click on the React JS infinite render component to load more items

Just diving into the world of react/next and I'm a bit stuck on this issue. I've searched high and low, tried different solutions, but I can't seem to figure out what I'm missing or not grasping here. I understand that loadStats() is ...

Is it possible for the Nextjs application to run in the background using the command line?

Looking for a way to run my Nextjs code in the background on Linux: Running command: npm run dev // Result is working fine at http://localhost:3000 However, running in the background with pm2 start npm --name "nextjs-13" -- start // Application does not w ...