The use of the import statement outside a module is not allowed when using jest testing

I recently encountered an issue while using jest to run tests on a library. After upgrading the library to export to es6, I started receiving the error message "Cannot use import statement outside a module," even though the tests were working fine before the upgrade.

Here is a screenshot of the error: https://i.sstatic.net/EeHZn.png

Below are the configuration files I'm using:

jest.config.js:
module.exports = {
  roots: ['<rootDir>/src/'],
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },
  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.ts?$',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
};
tsconfig.json:
{
  "compilerOptions": {
    ... (omitted for brevity)
  }
}
babel.config.js:
module.exports = {
  presets: [
    ... (omitted for brevity)
  ],
  plugins: [
    ... (omitted for brevity)
  ],
  env: {
    development: {},
    production: {
      ... (omitted for brevity)
    },
    test: {
      sourceMaps: 'both',
    },
  },
};

Despite trying various solutions found online, none of them have resolved the issue. If anyone has a solution or suggestions, it would be greatly appreciated. Thank you in advance!

Answer №1

Issue

An issue frequently encountered is when using the import statement with an esm JavaScript style, particularly with the sip.js package.

Resolution

A common solution involves configuring jest to transform the package using the transformIgnorePatterns option and also instructing tsc to compile the esm package.

To address this problem, follow these steps:

jest.config.js

module.exports = {
  // ...
  transform: {
    '^.+\\(t|j)sx?$': 'ts-jest', // transpile both `ts` + `js` files
  },
  transformIgnorePatterns: [`/node_modules/(?!(sip\.js))`] // Ensure `sip.js` is transpiled as well
};

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

Issue: Unable to locate API compiler-cli, function __NGTOOLS_PRIVATE_API_2

I am currently working on an Angular project and encountered the following errors, $ ng serve Your global Angular CLI version (8.3.21) is higher than your local version (7.0.7). The local Angular CLI version will be used. To disable this warning, us ...

Material UI TreeView: Organize and present node data with multiple columns in a tree structure

const treeItems = [ { id: 1, name: 'English', country: 'US', children: [ { id: 4, name: 'Spring', country: 'Uk', ...

Why is my Angular 2 app (TypeScript) not functioning properly?

My current project includes a component called EventListComponent import { Component } from 'angular2/core'; @Component ({ selector: 'el-events', templateUrl: 'app/events/event-list.component.html' }) export class E ...

Tips on providing validation for either " _ " or " . " (select one) in an Angular application

I need to verify the username based on the following criteria: Only accept alphanumeric characters Allow either "_" or "." (but not both) This is the code snippet I am currently using: <input type="text" class="form-control" [ ...

Unable to correctly import a TypeScript class into a React project

I have encountered an issue where I am unable to assign a default value to a TypeScript Class in my React Project (Docusaurus). It works with: class Test { private hello: string; constructor() { this.hello = "hi"; } } However, it does ...

Leverage Angular's filtering capabilities with a variety of input options

I am in need of help with a filter for my simple list of people, where each person has a name and a first name. I want to be able to search for a specific field or both fields at the same time. https://i.sstatic.net/pPRjO.png The HTML code is as follows: ...

What is the best way to transfer the variant property of the material-ui TextField when using a higher-level React component?

I'm encountering difficulties with typing... Essentially, I have a wrapper React component for the @material-ui TextField but I am struggling with getting the typings correct for the variant property. Here's the main problem. Using @material-ui ...

Utilize an array of observables with the zip and read function

I'm struggling with putting an array of observables into Observable.zip. I need to create a function that reads values from this dynamically sized array, but I'm not sure how to go about it. Does anyone have any suggestions? import {Observable} ...

Issues with style not loading properly within innerHTML in Angular2

Currently, I am in the process of developing a page using Angular2/4 that includes a left navigation bar. To achieve reusability, I have separated this left menu into its own component and nested it within the main component. The objective is to utilize th ...

Unable to generate a preview of the image that has been uploaded [using the REST API

While attempting to upload from my Ionic App to the Codeigniter Rest Server, I encountered an issue where the image could not be previewed after it was opened. To guide me through the uploading process from the app's end, I followed this tutorial: Th ...

Definition of generic with recursive immutability

I created a type definition to ensure immutability of types and their properties all the way down. However, when I attempt to use this with a generic type, the compiler claims that the types do not overlap, preventing me from casting an object as immutable ...

Disabling specific time slots in the mat select functionality

I have a scenario where I need to display time slots at 30-minute intervals using Mat Select. export const TIME=["12:00 AM","12:30 AM","01:00 AM","01:30 AM","02:00 AM","02:30 AM","03:00 AM&qu ...

What is the process for retrieving an element from component interaction?

Is there a way to dynamically change the background color based on component interaction? I am looking for a method to compare the target element with the current element. For example, here is a hypothetical scenario: <span [style.background]=" ...

The error message "TypeError: Unable to access property 'ready' of undefined in IONIC2" is displayed

I am currently working on integrating the InAppBrowser in IONIC2. Successfully installed Browser Plugin ionic plugin add cordova-plugin-inappbrowser Here is my .TS code for opening the browser browser(url:string) { this.platform.ready().then(() => ...

Set the value obtained from a resolved promise to a mutable reference object in a React component

I am in the process of developing a random movie generator. I am utilizing an external API to retrieve a list of movies and then selecting one randomly from the returned data. The current implementation is as follows: export default function Page() { con ...

Changing the Value of an Input Element Dynamically in React: A Step-by-Step Guide

In a scenario where I have a component that takes an element, such as <input />, and I need to update its value programmatically after 15 seconds. Initially, I had the following approach in mind: const MyComponent = (myInput: JSX.Element) => { ...

Constructor not executing when using Object.create

Attempting to instantiate a class within a static method, I am using Object.create(this.prototype), which appears to be functioning correctly. Nonetheless, when I check the console, my property items is showing as undefined. The base class called model lo ...

Angular 9: The instantiation of cyclic dependencies is not allowed

After transitioning from Angular 8 to Angular 9, I encountered an issue with a previously functioning HTTP communication service. The error message now reads: Error: Cannot instantiate cyclic dependency! HttpService at throwCyclicDependencyError (core ...

Reworking, Fusion, Prompt, and NX, Tackling Import Problems with @lingui/macro - Unavailable Named Export 'createMacro'

Shoutout to itxch over on GitHub for helping me with the integration of Vite, Remix, and NX. Currently facing an error that reads: Error when evaluating SSR module /@fs/Users/joseasilis/Documents/programming/alertdown/nx/nx-remix-vite/libs/ui/src/template ...

Learn the process of typing a property that will be displayed as a dynamic HTML element component

Looking for a way to render an HTML element dynamically based on a prop in a React component? interface ButtonProps { children: ReactNode; className?: string; as?: string; <--- ? [key: string]: unknown; } const Button = forwardRef({ children, ...