I am experiencing import issues with ts-node/ts-jest and unable to import the necessary modules

I'm having trouble with a syntax error while trying to integrate mdast-util-from-markdown into my Jest tests for a TypeScript project. I am seeking a solution that does not involve using Babel.

The code functions properly when using ts-node.

Issue:

Running my Jest tests results in the following error:

Details:

/Users/dudeman/ac/_utils/md-hierarchical-parser/node_modules/mdast-util-from-markdown/index.js:2
export {fromMarkdown} from './lib/index.js'
^^^^^^

SyntaxError: Unexpected token 'export'

> 1 | import { fromMarkdown } from "mdast-util-from-markdown";

Current Setup

Configuration:

tsconfig.json:

{
  "compilerOptions": {
    "target": "es2017",
    "module": "commonjs", // Also tried "esnext"
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  },
  "include": [
    "src/**/*",
    "test/**/*"
  ]
}

jest.config.cjs (also attempted jest.config.js)

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  globals: {
    'ts-jest': {
      useESM: true
    }
  },
  moduleNameMapper: {
    '^(\\.{1,2}/.*)\\.js$': '$1'
  },
  transform: {
    '^.+\\.ts$': 'ts-jest'
  },
  extensionsToTreatAsEsm: ['.ts']
};

Runner

npx jest

NODE_OPTIONS='--loader ts-node/esm' npc jest

Tried Solutions

  • Adjusting module settings in tsconfig.json (e.g., changing to "esnext", "commonjs")
  • Modifying jest.config.js to
    • handle ES module syntax,
    • transformIgnorePatterns: ['<rootDir>/node_modules/(?!unist-util-visit)'],
  • Attempted using Babel, despite preferring not to, and still encountering the error :/

Question:

How can I configure Jest and TypeScript to work seamlessly with mdast-util-from-markdown without facing the 'Unexpected token' issue, preferably without introducing Babel into my setup?

Edit:

Found success with:

tsconfig.json

{
  "compilerOptions": {
    "strict": true,
    "target": "ES2022",
    "module": "esnext",
    "moduleResolution": "node",
    "lib": ["esnext"],
    "types": ["node", "jest"],
    "skipLibCheck": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "declaration": true,
    "allowSyntheticDefaultImports": true
  },
  "ts-node": {
    "experimentalSpecifierResolution": "node",
    "transpileOnly": true,
    "esm": true,
  },
  "exclude": ["node_modules", "lib"]
}

jest.config.js

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  transform: {
    '^.+\\.{ts|tsx}?$': ['ts-jest', {
      useESM: true
    }],
  },
  moduleNameMapper: {
    '^(\\.{1,2}/.*)\\.js$': '$1'
  },
  extensionsToTreatAsEsm: ['.ts']
};

package.json

  "type": "module",
  "dependencies": {},
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^6.13.1",
    "@typescript-eslint/parser": "^6.13.1",
    "@types/jest": "29.5.10",
    "eslint": "^8.55.0",
    "jest": "29.7.0",
    "ts-jest": "29.1.1",
    "ts-node": "^10.9.1",
    "typescript": "^5.2.2"
  }

jest --env=node --colors --coverage test

Answer №1

react-markdown has a multitude of dependencies that need to be excluded in the Jest configuration:

// jest.config.js

const config = {
  transformIgnorePatterns: [
    '[/\\\\]node_modules[/\\\\](?!(bail|ccount|character-entities|comma-separated-tokens|decode-named-*|escape-string-regexp|hast-util-*|is-plain-obj|markdown*|mdast-util-*|micromark*|property-information|react-markdown|remark-*|space-separated-*|trim-lines|trough|unified*|unist-util-*|vfile))',
  ],
};

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

Tips for showing JSON information in Nativescript

How can I display all values in a page using the provided JSON data? res { "StatusCode": 0, "StatusMessage": "OK", "StatusDescription": [ { "sensors": [ { "serial": "sensor1", "id": "1" }, ...

Tips for restricting User access and displaying specific sections of the menu

I have a component that utilizes map to display all menu parts. Is there a way to make certain parts of the menu hidden if the user's access rights are equal to 0? const Aside: React.FunctionComponent = () => { const[hasRight, setHasRight] = us ...

Incorporating a TypeScript module into a JavaScript module within a React application

I'm encountering an issue with my React app that was created using create-react-app. I recently added a Typescript module to the project, which is necessary for functionality reasons. Although it will remain in Typescript, I made sure to install all t ...

Encountering Error with NodeJS Typescript: Issue with loading ES Module when running sls offline command

I have come up with a unique solution using NodeJS, Typescript, and Serverless framework to build AWS Lambdas. To debug it locally in VS Code, I use the serverless-offline library/plugin. You can find my project on GitHub here However, when I run the comm ...

Using Angular to handle routes with a specific domain prefix

Let's say I own the domain https://example.com and I'd like to create a subdomain specifically for my blog, like this: https://blog.example.com. How would you handle the routing for this scenario using Angular? ...

Encountered an issue while trying to run a React test in jest, the

I'm facing an issue while trying to execute jest tests, as I keep encountering the following error: 'jest' is not recognized as an internal or external command, operable program, or batch file. I have included my package.json below, and I ...

How can I pass an array of string inputs into Vue 3?

Working with Vue 3, I'm setting up a form that will display text input fields corresponding to a fixed-length array of strings. Each field's v-model should connect to the respective string in the array. Here is my current code snippet for the vie ...

What is the best way to ensure that the operations are not completed until they finish their work using RX

Is there a way to make RXJS wait until it finishes its work? Here is the function I am using: getLastOrderBeta() { return this.db.list(`Ring/${localStorage.getItem('localstorage')}`, { query: { equalTo: fa ...

Extract data from a string and assign it to a variable representing an

I have a custom function that parses a string and converts numbers and boolean values to their appropriate JavaScript primitives. This function is specifically designed for working with query parameters: const parseQueryParams = (searchString: string) => ...

Unable to utilize material tabs in this situation

Discovering the material tabs feature at https://material.angular.io/components/tabs/api#MatTab got me excited to implement it in my project. After adding the suggested import, I encountered an issue where I couldn't find the module "@angular/materia ...

TypeScript does not recognize the $.ajax function

Looking for help with this code snippet: $.ajax({ url: modal.href, dataType: 'json', type: 'POST', data: modal.$form.serializeArray() }) .done(onSubmitDone) .fail(onSubmitFail); ...

Exploring the realm of Typescript custom decorators: The significance behind context

I'm currently working on a custom decorator that will execute decorated functions based on RxJS events. Everything seems to be going well so far, but I'm facing an issue when the function is executed: the context of the this object is lost. I&a ...

elimination of nonexistent object

How can I prevent releasing data if two attributes are empty? const fork = [ { from: 'client', msg: null, for: null }, { from: 'client', msg: '2222222222222', for: null }, { from: 'server', msg: 'wqqqqqqqq ...

"Learn the trick of converting a stream into an array seamlessly with RxJs.toArray function without the need to finish the

In order to allow users to filter data by passing IDs, I have created a subject that can send an array of GUIDs: selectedVacancies: Subject<string[]> = new Subject(); selectedVacancies.next(['a00652cd-c11e-465f-ac09-aa4d3ab056c9', ...

Encountering challenges with the search and filtering features

I'm having some trouble with the search and filter features I'm creating. They work fine initially, but once I enter a search query in the input field, the results show up as expected. However, if I delete the query or enter a different one, the ...

Guide to encapsulating a container within a map function using a condition in JSX and TypeScript

Currently, I am working with an array of objects that are being processed by a .map() function. Within this process, I have a specific condition in mind - if the index of the object is greater than 1, it should be enclosed within a div element with a parti ...

Converting axios response containing an array of arrays into a TypeScript interface

When working with an API, I encountered a response in the following format: [ [ 1636765200000, 254.46, 248.07, 254.78, 248.05, 2074.9316693 ], [ 1636761600000, 251.14, 254.29, 255.73, 251.14, 5965.53873045 ], [ 1636758000000, 251.25, 251.15, 252.97, ...

Having trouble reaching a public method within an object passed to the @Input field of an Angular component

My configurator object declaration is as follows. export class Config { constructor(public index: number, public junk: string[] = []) { } public count() : number { return this.junk.length; } } After declaring it, I pass it into the input decorated fi ...

What is the most efficient way to execute useEffect when only one specific dependency changes among multiple dependencies?

My main objective is to update a state array only when a specific state (loadingStatus) undergoes a change. Yet, if I include solely loadingStatus as a dependency, React throws an error requesting all dependencies [loadingStatus, message, messageArray, set ...

Restricting enum type to only one member

enum Value { First, Second, } interface Data { value: Value number: number } interface SubData { value: Value.Second } function calculation(input: SubData){ return; } function initiate(){ const input : Data = { numbe ...