Issue with Importing 'tiny-secp256k1' Library in Jest with Typescript

I have recently integrated the npm package tiny-secp256k1 into my project.

This package offers non-default exports of various functions, each with type declaration included.

Despite multiple attempts to import it and run my test suite using Jest, I keep encountering the following error:

    /pathToProject/node_modules/tiny-secp256k1/lib/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { compare } from "uint8array-tools";
                                                                                      ^^^^^^

SyntaxError: Cannot use import statement outside a module

It is unclear whether this issue stems from the library itself or if it is related to my project configuration. Other libraries can be imported without any issues.

Here is an excerpt from my jest.config.ts:

export default {
    verbose: true,
    transform: {
        '^.+\\.(ts|tsx)?$': 'ts-jest',
    },
    testPathIgnorePatterns: ['__tests__/helpers'],
};

And here is a snippet from my tsconfig.json:

{
    "compilerOptions": {
        "target": "ES2020",
        "module": "commonjs",
        "outDir": "dist",
        "allowJs": false,
        "sourceMap": true,
        "resolveJsonModule": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true
    },
    "exclude": ["__tests__/"]
}

Answer №1

I had been facing a similar issue for quite some time. It seems to be related to jest and the peculiar behavior with "cjs" modules. Although I couldn't pinpoint the exact reason behind it, my research led me to a post (Jest won't transform the module - SyntaxError: Cannot use import statement outside a module) that provided me with some insight on how to resolve it. Below is the content of my jest.config.js file which successfully addresses this problem:

module.exports = {
    preset: "ts-jest",
    moduleFileExtensions: [
        "ts",
        "js",
        "cjs",
        "mjs"
    ],
    transform: {
        "^.+\\.(ts|tsx)$": "ts-jest",
        "node_modules/tiny-secp256k1/lib/cjs/.+\\.(js|ts|cjs|mjs)$": "ts-jest",
        "node_modules/uint8array-tools/src/cjs.+\\.(js|ts|cjs|mjs)$": "ts-jest"
    },
    moduleNameMapper: {
        "^uint8array-tools$": "uint8array-tools/src/cjs",
        "^tiny-secp256k1$": "tiny-secp256k1/lib/cjs"
    },
    transformIgnorePatterns: [
        "node_modules/(?!tiny-secp256k1/lib/cjs/.*)",
        "node_modules/(?!uint8array-tools/src/cjs/.*)"
    ],
    testMatch: [
        "**/test/**/*.test.(ts|js)"
    ],
    testEnvironment: "node"
};

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 is the best way to open and view files in an NPM dependency that do not use JavaScript?

I am facing an issue with an NPM project setup where my-config is a dependency of my-api. In the my-config project, there is a line of code that fetches the aws-config.ini file from the etc folder: instance.configs.aws = ini.parse(fs.readFileSync('./ ...

Styling in Svelte/TS does not change when applied through a foreach loop

I've been experimenting with creating a unique "bubble" effect on one of my websites, but I'm facing difficulty changing the styling in a foreach loop. Despite no errors showing up in the console, I'm at a loss as to how to effectively debu ...

`Troubleshooting problem with debugging mocha tests in a TypeScript environment`

I'm currently facing an issue while trying to debug a mocha test. Despite my efforts in searching on Google and Stack Overflow, I have not been able to find a solution. The error message is as follows: TSError: ⨯ Unable to compile TypeScript: sour ...

Is there a way to automatically scroll to the bottom of a div when it first

Looking to enhance my application with a chat feature that automatically scrolls to the bottom of the chat page to display the latest messages. Utilizing VueJs: <template> <div id="app"> <div class="comments" ...

Transform a callback-based function into an Async Iterator version

Situation I have a function with an asynchronous callback structure, like so: let readFile: (path: string, callback: (line: string, eof: boolean) => void) => void However, I would much rather use a function that follows the AsyncIterable/AsyncGen ...

Attempting to transform calc application into TypeScript, what data type should this function be?

Currently in the process of converting a calculator app to TypeScript. I've noticed that TypeScript is not prompting me to define the types for the three functions (handleClick, handleEqual, handleClear). Is specifying the type for the argument eno ...

Issue with Angular 7 cli failing to recognize a custom TypeScript file

While working on an Angular 7 component, I encountered an issue when trying to read a custom file. The problem arises when the server restarts, even though there are no errors in the component's TypeScript file. ERROR: app/zontify-components/zonti ...

Why is it important to use linting for JavaScript and TypeScript applications?

Despite searching extensively on Stack Overflow, I have yet to find a comprehensive answer regarding the benefits of linting applications in Typescript and Javascript. Any insights or resources would be greatly appreciated. Linting has become second natur ...

Setting a data type for information retrieved from an Angular HTTP request - A Step-by-Step Guide

Here is the code I use to fetch data: login() { const url = api + 'login'; this.http.post(url, this.userModel) .subscribe( data => { localStorage.token = data.token; this.router.navigate(['/home&a ...

What are some effective ways to utilize the data gathered from a subscribe() method in a different

handleKeyUp(event: any): void { this.technologiesService.retrieveData(event.target.value) .subscribe(data => { this.myResults = data; }); } The result of data is: https://i.sstatic.net/WjiD4.png I want to assign data as a property fo ...

Encountering difficulties while trying to set up Node-Inspector in Windows Terminal

Recently, I've started exploring NodeJS and attempted to set up Node-Inspector on my Windows terminal. However, I encountered an error during the installation process. PS C:\Users\rahul> npm install -g node-inspector npm WARN deprecated ...

An error has been detected: An unexpected directive was found. Kindly include a @NgModule annotation

I am encountering an issue while trying to import a class into a module in my Ionic/Angular app. Upon attempting to release, the following error message appears: ERROR in : Unexpected directive 'SeedModalPage in /home/robson/Lunes/repositories/bolunes ...

Are there any more clever methods to use npm?

In my understanding, the way npm handles module dependencies is by allowing each module to require everything as a tree. This results in duplicating dependencies if multiple modules use the same one. Is there a smarter node package manager that can organiz ...

Using an asynchronous pipe filter with the ngFor loop in Angular 2 for efficient data

I have a JSON array that I need to iterate through in order to display data using an NGfor Loop. My goal is to apply filters after the data has been loaded to refine the results. The issue I am facing is that my pipe filter is returning 'cannot read p ...

I am unable to utilize ES6 modules alongside typescript in my Node.js project

My Node.js project requires the use of both typescript and es6 modules for compiling files to javascript. The desired outcome is to have the files compiled in javascript with the es6 module. Below is the content of my package.json : { "name": ...

Meteor fails to install useraccounts:bootstrap package due to npm.depends error

Every time I attempt to integrate useraccounts:bootstrap into my meteor project, an error message pops up... Error: 'request' npm module not found. Have you remembered to include 'Npm.depends' in package.js under the 'http' p ...

Guide for specifying type when passing a component as a prop

Struggling to successfully pass a component as a prop to a straightforward functional component called RenderRoute: interface RouteProps { component: React.ComponentType; isProtected: boolean; isLoggedIn: boolean; path?: string; exact?: boolean; ...

Utilize TypeScript to import a JSON file

I am trying to incorporate a JSON file using TypeScript, which contains data about different regions in Italy along with their respective capitals. Here is a snippet of the data: { "italia": [ { "regione": "Abruzzo", "capoluoghi": [ ...

Error: Certain Prisma model mappings are not being generated

In my schema.prisma file, I have noticed that some models are not generating their @@map for use in the client. model ContentFilter { id Int @id @default(autoincrement()) blurriness Float? @default(0.3) adult ...

The 'mergeMap' property is not found on the 'Observable<any>' type

Currently, I'm working on an HttpInterceptor within my Ionic 4 application. My goal is to retrieve the Bearer Authorization token stored in local storage. Although I attempted to utilize mergeMap for this task, I kept encountering the following error ...