Jest test encounters import error when attempting to import pure ESM module in TypeScript project

Hello, I am currently facing an issue while trying to utilize the file-type module, which is pure ESM, in a TypeScript project with Jest. Despite following the ESM guidelines outlined here, I continue to encounter a

SyntaxError: Cannot use import statement outside a module
error.

To better illustrate my problem, I have created a sandbox that you can access here.

Here is a summary of my code:

import { fileTypeFromBuffer } from "file-type";

Below is a snippet of my Jest configuration:

export default {
  testEnvironment: "jest-environment-node",
  globals: {
    extensionsToTreatAsEsm: [".ts"],
    "ts-jest": {
      useESM: true,
    },
  },
  transform: {
    "^.+\\.(ts|tsx|js|jsx)?$": "ts-jest",
  },
  moduleNameMapper: {
    "^(\\.{1,2}/.*)\\.js$": "$1",
  },
  preset: "ts-jest",
};

Furthermore, here is my TSConfig setup:

{
  "extends": "@tsconfig/node14/tsconfig.json",
  "compilerOptions": {
    "target": "ES2018",
    "module": "commonjs",
    "lib": ["es2018"],
    "declaration": true,
    "strict": true,
    "strictNullChecks": true,
    "alwaysStrict": true,
    "noImplicitReturns": false,
    "noImplicitThis": false,
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "noEmit": true,
    "noFallthroughCasesInSwitch": false,
    "inlineSourceMap": true,
    "inlineSources": true,
    "experimentalDecorators": true,
    "strictPropertyInitialization": false,
    "resolveJsonModule": true,
    "outDir": "dist",
    "baseUrl": ".",
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}

If you have any insights or suggestions on how to resolve this, I would greatly appreciate it. Thank you!

Answer №1

In order for Jest to transform ESM bundled libraries, you must specify the paths to ignore using the transformIgnorePatterns option.

By default, this option includes paths like

["/node_modules/", "\\.pnp\\.[^\\\/]+$"]
, which is why the libraries are not transformed.

A simple solution is to set this option to an empty array:

transformIgnorePatterns: []

Alternatively, you can configure a more detailed rule to exclude all libraries except for specific ones, as shown in the regular expression example in the documentation.

Additionally, ensure you include the "allowJs": true option in your TypeScript configuration.

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

Is there a method available that functions akin to document.getelementbyid() in this specific scenario?

Currently, I am tackling a project that involves implementing a search function. My initial step is to ensure that all input is converted to lowercase in order to simplify SQL calls. However, I have encountered a challenge that is proving difficult for me ...

Setting up a Form submit button in Angular/TypeScript that waits for a service call to finish before submission

I have been working on setting up a form submission process where a field within the form is connected to its own service in the application. My goal is to have the submit button trigger the service call for that specific field, wait for it to complete suc ...

What is the significance of default parameters in a JavaScript IIFE within a TypeScript module?

If I were to create a basic TypeScript module called test, it would appear as follows: module test { export class MyTest { name = "hello"; } } The resulting JavaScript generates an IIFE structured like this: var test; (function (test) { ...

Using Partial function input in TypeScript

I am in need of a function that can accept partial input. The function includes a variable called style, which should only have values of outline or fill, like so: export type TrafficSignalStyle = 'outline' | 'fill' let style: TrafficSi ...

Sending data from child components to parent components in Angular

I'm facing an issue with retrieving data from a child array named store within user data returned by an API. When trying to access this child array in my view, it keeps returning undefined. Code export class TokoPage implements OnInit { store= nu ...

Issues with the functionality of Angular 2 routerLink

Unable to navigate from the homepage to the login page by clicking on <a routerLink="/login">Login</a>. Despite reviewing tutorials and developer guides on Angular 2 website. Current code snippet: index.html: <html> <head> ...

When using Array.find() in TypeScript, the Subscribe function does not get called

I am currently diving into Typescript and web development, but I've encountered a peculiar issue when subscribing to an event that's leaving me stumped. In my service, I'm using a BehaviorSubject to store a carId, and on a page where there&a ...

Having trouble getting a Custom React Component from an external library to work with MUI styling

I am currently working with a React component that comes from a module located in the node_modules folder: type Props = { someProps: any }; export function ComponentA(props: Props) { const [value, setValue] = React.useState(""); return ( <Te ...

Issue during Firebase production: emptyChildrenSingleton isn't recognized

In my nextjs project, I am using React v18.1.0 and Firebase Realtime Database for handling notifications. The notifications work fine in development mode but fail in the production environment. The errors I encountered are as follows: ReferenceError: empt ...

How can esbuild be used to load .wglsl files in Typescript files?

I'm currently utilizing esbuild to bundle my Typescript code, but I'm facing a challenge with configuring a loader for ".wgsl" files. Here is my app.ts file: import shader from './shader.wgsl'; //webgpu logic This is my shader.d.ts fi ...

Each time the website refreshes, Object.entries() rearranges the orders

After reading the discussion on Does JavaScript guarantee object property order? It seems that Object.entries() should maintain order. However, I encountered an issue with my Angular website where the order of keys in Object.entries() changed upon refres ...

The specified target "TypeScriptClean" is not present within the project

I'm facing some issues in Visual Studio 2017 Professional. Despite not having any TypeScript code in my solution, I am encountering numerous TypeScript-related errors during the build process. The main error message that keeps popping up is: The targ ...

Obtaining a value from HTML and passing it to another component in Angular

I am facing an issue where I am trying to send a value from a web service to another component. The problem is that the value appears empty in the other component, even though I can see that the value is present when I use console.log() in the current comp ...

Utilizing NextJS to efficiently route requests directly to the backend and send the responses back to the client within the

In the technology stack for my project, I am using a Next.js server for the front end and a separate back-end server to handle user data storage. When a client needs to send a request to the back end, they first make an API request to the Next.js server, ...

Prisma: Utilizing the include option will retrieve exclusively the subobject fields

I created a function to filter the table building and optionally pass a Prisma.BuildingInclude object to return subobjects. async describeEntity(filter: Filter, include?: Prisma.BuildingInclude): Promise<CCResponse> { try { const entity = await ...

"Unexpected compatibility issues arise when using TypeScript with React, causing errors in props functionality

Just the other day, my TypeScript+React project was running smoothly. But now, without making any changes to the configurations, everything seems to be broken. Even rolling back to previous versions using Git or reinstalling packages with NPM does not solv ...

Getting started with TypeScript in combination with Node.js, Express, and MongoDB

I'm a beginner in working with TypeScript, Node.js, Express, and MongoDB. I need guidance on the end-to-end flow for these technologies. Can someone please suggest steps or provide links for a step-by-step process? What is the procedure to compile/r ...

Accessing file uploads in Angular 2

<div class="fileUpload btn btn-primary"> <span>Select File</span> <input id="uploadBtn" type="file" class="upload" value="No File Chosen" #uploadBtn/> </div> <input id="uploadFile" placeholder="No File Selected" disable ...

Adding a new document to an existing collection with an array field in MongoDB

Having an issue with adding a new chapter to my var array. Here is the code snippet in question: array.push({ chapter: [ { id: 2, title: 'adsf', content: &ap ...

Issues with utilizing destructuring on props within React JS storybooks

I seem to be encountering an issue with destructuring my props in the context of writing a storybook for a story. It feels like there may be a mistake in my approach to destructuring. Below is the code snippet for my component: export function WrapTitle({ ...