When using next.js, typescript, and jest together, an error may occur with the message "Unexpected token '

When attempting to run jest in my Typescript Next.js project, I encounter the following error:

    Details:

    node_modules/d3-scale/src/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export {
                                                                                      ^^^^^^

    SyntaxError: Unexpected token 'export'

       7 | import { useRouter } from 'next/router';
       8 | import { gql } from '@apollo/client';
    >  9 | import { scaleLinear } from 'd3-scale';

I have already attempted to include d3-scale in transformIgnorePatterns within my jest configuration.

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

const createJestConfig = nextJest({
  dir: './',
});
const customJestConfig = {
  moduleDirectories: ['node_modules', '<rootDir>/'],
  testEnvironment: 'jest-environment-jsdom',
  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
  testPathIgnorePatterns: ['<rootDir>/.next/', '<rootDir>/node_modules/', '<rootDir>/pages/test.tsx'],
  moduleNameMapper: {
    '\\.(scss|sass|css)$': 'identity-obj-proxy',
  },
  transform: {
    '\\.[jt]sx?$': 'babel-jest',
  },
  transformIgnorePatterns: [
    '/node_modules/(?!d3-scale)',
  ],
};
module.exports = createJestConfig(customJestConfig);

Answer №1

In Next.js, it's not possible to directly override the transformIgnorePatterns, but you can extend it with a workaround.

To achieve this, you can modify your jest.config.js file like so:

async function customizeJestConfig() {
  const nextJestConfig = await generateJestConfig(customJestConfig)()
  nextJestConfig.transformIgnorePatterns[0] = '/node_modules/(?!d3-scale)/'
  return nextJestConfig
}

module.exports = customizeJestConfig
//module.exports = generateJestConfig(customJestConfig)

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 resources are available for creating the framework of a TypeScript package in DefinitelyTyped?

I am interested in making contributions to by providing new types similar to what can be found on https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types. I believe there must be a way to create a package from scratch or get started. I have ...

Is it possible to incorporate JavaScript files into a TypeScript (ts, tsx) project that has already been built?

Recently, I was given a task to incorporate additional pages into the current project which has been developed using the following technologies: Laravel: 8.12 React: 17.0.2 NextJS: 10.0.9 Tailwind CSS: 2.0.4 React Query: 3.13.0 [ REST] TypeScript: 4.2.3 M ...

"TypeScript error: Arrays in interfaces are found to be undefined and not compatible

I'm struggling with correctly implementing the Typescript React Props syntax. In my project, I have an array of people, each of whom may have zero to many cars. There is a people container that holds all the people, each person has a car container tha ...

Troubleshooting issues with JSON data in d3 Sankey charts

I seem to be encountering an issue with creating a graph and could really use some assistance. I am attempting to create the following chart: http://bl.ocks.org/wvengen/cab9b01816490edb7083 However, every time I try, an error occurs and causes the browser ...

Alert: Using Angularfire SDK could result in console log issues

I've been encountering this persistent warning that I just can't seem to get rid of no matter what I try. Here are the versions I'm using: angular 11.0.1 @angular/fire 6.1.3 firebase 7.0.0 || 8.0.0 https://i.sstatic.net/5Tyt5.png ...

What is the process for automatically initiating a service when importing a module in Angular?

I am curious about how I can automatically run a service within a module upon importing it, without the need for manual service injection and execution. This functionality is similar to how the RouterModule operates. @NgModule({ imports: [ Browser ...

Monitoring the parent's CSS attribute in Angular 2

One of my directives dynamically adds the number of pixels corresponding to its parent element's right CSS attribute. import { Directive, ElementRef, AfterViewInit } from "angular2/core" @Directive({ selector: "[d]" }) export class Positioni ...

Leveraging ArangoJS Driver within an Angular2 web platform

Currently, I am in the process of working on a project that involves Angular2 and Typescript (v1.8.10). Our aim is to incorporate data from an ArangoDB database into the web application. Ideally, I would like to utilize the arangojs driver for this task. H ...

Is there a way to seamlessly integrate expect() with regular promises in protractor promise sequences?

As I dive into the world of promises in protractor, I find myself puzzled by the execution order, especially when mixing non-protractor promises with protractor promises. My goal is to troubleshoot and resolve some inconsistent protractor tests at my workp ...

Afterward, Vercel disconnects from Supabase, causing the connection to be dropped

Over the past month, there have been recurring issues with Vercel dropping the connection to Supabase on a daily basis. The support team at Supabase claims that the error ('user not found - and the auth tool is supabase/auth') is not related to ...

Eliminating the need for RequireJS in the Typescript Visual Studio project template

After integrating RequireJS into my Typescript template using the nuget package manager, I found that it was more than what I needed and decided to uninstall it. Even though I removed the package through nuget and the files were deleted properly, my Typesc ...

Scrolling through a list in Angular using cdk-virtual-scroll-viewport while selecting items via keyboard input

Looking to implement a customized Autocomplete feature. As the user begins typing, a small window should appear with selectable options. I want users to have the ability to navigate and select an option using their keyboard. For instance: - User types "H ...

Understanding how to extract an enum from a string and its corresponding value in TypeScript

I am working with a simple enum called errorCode, shown below: export enum SomeErrorCodes { none = 0, notFound = 1, duplicated = 2 } Currently, I am receiving the name of the enum as a string "SomeErrorCodes" and a number, for example, 1. How ...

Angular loop is unable to detect changes in the updated list

My Angular application is facing a peculiar issue that I can't seem to figure out. // Here are the class attributes causing trouble tenants: any[] = []; @Input() onTenantListChange: EventEmitter<Tenant[]>; ngOnInit(): void { this. ...

How to Implement a Conditional back Button in Next.js

I have a page '/message/:id' that includes a back button on the top left. The button currently utilizes the router.back() function and works well when I navigate to the page from any other screen. However, I am also sending notifications which, u ...

Unable to retrieve the reflective metadata of the current class instance

Is it possible to retrieve the reflect-metadata from an instance of a class? The documentation provides examples that suggest it should be achievable, but when I attempt to do so, I receive undefined as a result. Strangely enough, when I request the metada ...

When attempting to utilize SSR Portals with Next.js, an error may occur if the portals

My Next.js application is experiencing a random fatal error that necessitates restarting Node to resolve. The compressed error points to this URL: https://reactjs.org/docs/error-decoder.html/invariant=257 Oddly, I do not incorporate Portals anywhere in m ...

Is the Scope Staying Static in AngularJS 1.4 when Input Text Changes and Two-Way Binding is Enabled?

Encountering a strange issue with AngularJS 1.4 (TypeScript). The problem lies within the controller where a variable is set and displayed in an input text box. Oddly, when attempting to edit the value in this text box and clicking on a button, the variabl ...

Encountering Next.js Hydration Issue when Using Shadcn Dialog Component

While working on a Next.js project, I came across a hydration error when utilizing the Shadcn Dialog component. The specific error message reads: "Hydration failed because the initial UI does not match what was rendered on the server." Highligh ...

Issues with Cross-Origin Resource Sharing (CORS) have been identified on the latest versions of Android in Ionic Cordova. However, this problem does not

I am encountering an issue with my TypeScript Ionic code. It works well in browsers and some older mobile devices, but it fails to function on newer Android versions like 8+. I need assistance in resolving this problem. import { Injectable } from '@an ...