Failing NodeNext Tests with TypeScript and ES2022

In the code snippet below, I am showcasing a problem that I am currently facing in my project.

The code transpires and executes, but it fails to compile with jest due to the following error:

Error: error TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'.

Files: src/calc.ts


import { fileURLToPath } from 'url';
import path from 'path';
const __dirname = path.dirname(fileURLToPath(import.meta.url));

export function add(x: number, y: number): number {
  return x + y;
}

export function mul(x: number, y: number): number {
  return x * y;
}

jest.config.cjs:


module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
};

tsconfig.json:


{
  "include": [
    "./src/**/*"
  ],
  "exclude": [
    "node_modules"
  ],
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "outDir": "./out",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}

package.json


"devDependencies": {
  "@types/jest": "^26.0.24",
  "jest": "^26.6.3",
  "ts-jest": "^26.5.6",
  "typescript": "^4.7.4"
}

I'm not certain if I'm making any mistakes here.

Answer №1

After investigating the issue with running the tests using Jest, I have identified the cause of the error but am unsure how to resolve it.

The

"module": "NodeNext"
setting is not being recognized because Jest configures ts-node with
"module": "CommonJS"

/// packages/jest-config/src/readConfigFileAndSetRootDir.ts

    // Register TypeScript compiler instance
    const tsNode = await import('ts-node');
    return tsNode.register({
      compilerOptions: {
        module: 'CommonJS',
      },
      moduleTypes: {
        '**': 'cjs',
      },
    });

Refer to the source code for Jest for more details.

This discrepancy is why the error message mentions that nodenext is a valid choice even though it was specified in your tsconfig.json.

Answer №2

Personally, I made the choice to go with a bun instead

Answer №3

While this solution may not be the one that directly addresses the issue at hand, I opted to utilize Node's built-in test runner instead of jest runner from LTS 20 onwards (not everyone may have access to this option). This approach resolved the issue for me as it provides a more streamlined method for executing tests and allows for transpilation of code using tsc for testing purposes.

Answer №4

My testing setup involves using ts-jest.

In order to make it work, I had to make adjustments in the jest.config.js file and rename it to jest.config.ts

After that, I updated the new jest.config.ts file to function as an ESM module by incorporating the following code:

import type { JestConfigWithTsJest } from 'ts-jest'

const jestConfig : JestConfigWithTsJest = {
  bail: true,
  verbose: true,
  collectCoverage: true,
  testTimeout: 10000,
  collectCoverageFrom: ['src/**/*.ts'],
  coveragePathIgnorePatterns: ['\\.d\\.ts$'],
  modulePathIgnorePatterns: [
    'node_modules/',
    'dist/'
  ],
  preset: 'ts-jest/presets/default-esm',
  testEnvironment: 'node',  
}

export default jestConfig

Additionally, I made sure to switch the value of the preset property from:

preset: 'ts-node'

to

preset: 'ts-jest/presets/default-esm' 

If you are facing similar issues, please refer to the preset link mentioned below for guidance on configuring your setup:

Wishing you all the best with your testing endeavors.

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

Incorporate a personalized button within the actions column of ng2-smart-table for Angular 2 development

Within the context of an ng2-smart-table component in Angular 2, I am attempting to include a new button within the actions column that, when clicked, will navigate to another page. Despite my efforts to implement this new button alongside the existing add ...

Troubleshooting React Native in VS Code using Node shims

I recently started working on a React Native project using the Ignite CLI 2.0.0 default boilerplate, and I find myself in need of some dependencies from node-based packages. To address this, I created files named transformers.js, babel-transform.js, and r ...

Converting a JSON array stored in a local file to a TypeScript array within an Angular 5 project

I'm currently working on developing a web app using Angular 5. My JSON file has the following structure: [ { "id": 0, "title": "Some title" }, { "id": 1, "title": "Some title" }, ... ] The JSON file is store ...

Tips for utilizing node transformation to convert an object into a different form

As someone new to Node streams, I'm currently experimenting with them and facing unexpected issues. My goal is to create a simple transform for practice. interface MyTransformStreamOptions { [key: string]: any } class MyTransformStream extends Tra ...

The creation of a parameterized function that doubles as an object property

interface item { first: string; last: string; } const itemList = Item[]; updateAttribute = (index, attributeToUpdate) => { itemList[index].attributeToUpdate = "New first/last" } The snippet above showcases an interface named item with propertie ...

The Generic Function's Return Type in Typescript

The latest addition of ReturnType in TypeScript 2.8 is a highly valuable feature that enables you to capture the return type of a specific function. function foo(e: number): number { return e; } type fooReturn = ReturnType<typeof foo>; // numbe ...

What is the process for obtaining the complete URL using the getDownloadURL() function along with a token?

An error occurred due to an unresolved FirebaseStorageError: "storage/object-not-found". The message indicates that the object 'k91a73uzb99' does not exist in Firebase Storage. This type of error is categorized under FirebaseError with a code of ...

Combine two JSON objects into a single JSON object within the ngOnInit function

I am dealing with an Angular component where, upon loading, two service methods are called to fetch data in JSON format. My goal is to merge these two sets of data together. After researching other solutions, I discovered that Object.assign could accomplis ...

What steps can be taken to transform a React Functional Component utilizing hooks into a class-based component?

Encountering roadblocks while attempting to convert a React Functional Component to a class. Below is the functional component code: import * as React from 'react'; import { withStyles } from '@material-ui/core/styles'; import Drawer ...

Using TypeScript to import the fs module

Although it may appear as a repeated question, none of the solutions I've come across seem to resolve the issue: Within my .ts file: import * as fs from 'fs'; // error: SyntaxError: Unexpected token * // OR import fs from 'fs'; / ...

Unlocking the essence of objects: extracting their types

Here's a map I have: const Map = { key1: 'value1', key2: 'value2' } I'm looking to create a type value1 | value2 using the object above. Is there a way to do this without repeating the values? I attempted type MyType = ...

Error when testing React Material UI: TypeError - Attempting to read property 'get' of undefined

I encountered an issue with the following code snippet: /* eslint-disable react/display-name */ import { Box, Button, LinearProgress, makeStyles } from '@material-ui/core'; import { Refresh } from '@material-ui/icons'; import { SearchHi ...

Is TypeScript the ultimate solution for function typing?

Currently delving into TypeScript, and I've got a query regarding annotating function types. Taking a look at this basic example: export const add = (num1: number, num2: number):number => { return num1 + num2; }; This seems well-typed to me. Ty ...

Creating definitions for generic static members within a third-party module

There is a 3rd party module with the following structure: export class Container{ static async action() { return {...} } constructor(params = {}) { // ... } async doSomething(params = {}) { // ... } } I am looking to de ...

In Angular 11, there is a potential for an object to be null

When running the code below, I encountered an error stating Object is possibly null in line +localStorage.getItem('PID'): newPropID() { if (localStorage.getItem('PID')) { localStorage.setItem('PID', String(+localStorage. ...

What is the best way to wait for the state to be set before mapping the array

I have some data stored in an array (shown in the screenshot below) that I am trying to map, but I am facing issues accessing it as it is loaded asynchronously. How can I await the data? Is there a way to achieve this within the render function? render() ...

When trying to integrate Angular.ts with Electron, an error message occurs: "SyntaxError: Cannot use import statement

Upon installing Electron on a new Angular app, I encountered an error when running electron. The app is written in TypeScript. The error message displayed was: import { enableProdMode } from '@angular/core'; ^^^^^^ SyntaxError: Cannot use impor ...

Dynamically assign routes using Node.js and Express framework

Having trouble dynamically assigning a new route, as it refuses to work. When sending a request in Postman, it just keeps waiting for a response. To provide some context, I have a controller with a decorator on one of its methods: @Controller() export cl ...

Failure to update values in local storage using the React useLocalStorage hook

I've developed two unique custom hooks named useLocalStorage and useAuth. function getDefaultValue<T>(key: string, initialValue: T | null): T | null { const storedValue: string | null = localStorage.getItem(key); if (storedValue) { retur ...

How can I provide type annotations for search parameters in Next.js 13?

Within my Next.js 13 project, I've implemented a login form structure as outlined below: "use client"; import * as React from "react"; import { zodResolver } from "@hookform/resolvers/zod"; import { signIn } from "n ...