Jest encountered an unexpected token + react markdown
Asked Answered
Q

9

32

I'm getting an error when trying to run my test file (I'm using react typescript)

  ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    export {uriTransformer} from './lib/uri-transformer.js'
    ^^^^^^

    SyntaxError: Unexpected token 'export'

       5 | const Markdown = ({ text, classStyle }: ITextMedia) => (
       6 |   <div className={`${classes.mediaParagraph} ${classStyle ?? ''}`}>
    >  7 |     <ReactMarkdown>{text}</ReactMarkdown>
         |                                             ^
       8 |   </div>
       9 | );
      10 | export default Markdown;

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (components/media/markdown/index.tsx:7:45)

I already tried adding the React markdown to the transform ignore patterns, but it still doesn't work

here's my jest.config

{
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  moduleDirectories: ['node_modules', '<rootDir>/'],
  testEnvironment: 'jest-environment-jsdom',
  moduleNameMapper: {
    'next/router': '<rootDir>/__mocks__/next/router.js',
    '^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
    '^.+\\.(jpg|jpeg|png|gif|webp|avif|svg)$': '<rootDir>/__mocks__/file-mock.js',
  },
  transform: {
    '^.+\\.(js|jsx)$': 'babel-jest'
  },
  transformIgnorePatterns: [
    'node_modules/(?!react-markdown/)'
  ]
}

my babel config:

{
    "presets": [
        "next/babel",
        "@babel/preset-env"
    ],
    "plugins": []
}

I'm new to jest, so I'm not sure if I'm doing something wrong

Quartet answered 25/5, 2022 at 18:2 Comment(0)
D
48

In the jest.config file, you need to add the following to the moduleNameMapper attribute:

"react-markdown": "<rootDir>/node_modules/react-markdown/react-markdown.min.js"

So effectively, your moduleNameMapper should really look like this:

  ...
  moduleNameMapper: {
    'next/router': '<rootDir>/__mocks__/next/router.js',
    '^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
    '^.+\\.(jpg|jpeg|png|gif|webp|avif|svg)$': '<rootDir>/__mocks__/file-mock.js',
    'react-markdown': '<rootDir>/node_modules/react-markdown/react-markdown.min.js',
  },
  ...

Good luck!

Daughter answered 3/6, 2022 at 22:15 Comment(4)
thank you, that worked for me, can you explain why this step is needed?Shortlived
Hi @Anne, the purpose of the moduleNameMapper is essentially to stub out resources for the purpose of testing. But sometimes it can also be used to help Jest find the right modules to run tests with. In the case of react-markdown, it just needs a little help to point to the right directory to run the right file for the tests. I hope this helps.Daughter
Finally I found this solution working for me. Thank you!Obese
this doesn't work anymoreMillsaps
N
5

The following fix in jest.config.js no longer works from version 9.0.0 as they remove the bundle step.

  ...
  moduleNameMapper: {
    'react-markdown': '<rootDir>/node_modules/react-markdown/react-markdown.min.js',
  },
  ...
Naples answered 15/1, 2024 at 15:50 Comment(1)
so whats the solution?Millsaps
B
3

You need to add not only react-markdown to the transformIgnorePatterns, but also all its dependencies which are pure ESM.

When running your tests you can see the dependencies one by one in the jest error. Remember about ones inside react-markdown node_modules.

Details:

/{...}/node_modules/react-markdown/node_modules/comma-separated-tokens/index.js:23

Add one by one in the transformIgnorePatterns and run the tests again to get the next error.

You have to add the react-markdown, comma-separated-tokens, and others. It'll depend on the react-markdown version you use. In my case it was:

"transformIgnorePatterns": [
  "/node_modules/(?!comma-separated-tokens|space-separated-tokens|hast-util-whitespace|property-information|trim-lines|remark-rehype|remark-parse|trough|is-plain-obj|bail|unified|vfile|react-markdown)"
]
Bradawl answered 23/3, 2023 at 18:2 Comment(0)
L
3

I Recommend this solution only if you want the error to be ignored.

create an empty mock file - (empty-mock.ts in relevant folder)

const EmptyMock = {};

export default EmptyMock;

And map this to import modules to be ignored -

const customJestConfig = {
  moduleNameMapper: {
    //imports to be ignored by jest
    "react-markdown": "<rootDir>/mock/empty-mock.ts",
    "remark-gfm": "<rootDir>/mock/empty-mock.ts",
  },
};
Legality answered 7/3, 2024 at 18:1 Comment(0)
F
2

I had the same problem in my environment. We use nx in a monorepo and manage our packages with pnpm. Since pnpm caches modules by default, it does not work with the <rootDir>/node_modules/. However, you can also do without this path, then it works with pnpm as well (jest also mentions in its docs that the usage of <rootDir> is optional):

…
moduleNameMapper: {
  'react-markdown': 'react-markdown/react-markdown.min.js',
},
…
Fleurette answered 18/8, 2023 at 10:13 Comment(2)
Thank you so much, I've been trying everything I can for hours. This is the right path forward for me. I have react-markdown included through a 3rd party includeTriumphal
this doesn't work anymoreMillsaps
T
0

Its a simple fix in the code, just change the import statement from

import ReactMarkdown from 'react-markdown';

to

import ReactMarkdown from 'react-markdown/react-markdown.min';
Terrilyn answered 25/5, 2023 at 12:1 Comment(1)
this doesn't work anymoreMillsaps
A
0

I have the same problem for @uiw/react-markdown-preview plugin.

The only thing I can do it just add this under moduleNameMapper inside package.json

"react-markdown-preview": "<rootDir>/node_modules/@uiw/react-markdown-preview/dist/markdown.min.js"
Afterthought answered 26/9, 2023 at 10:3 Comment(0)
A
0

I too encountered this when using react-markdown v9.0.1. It seemed no amount of configuring did the trick until I started expanding on Fernanda Duarte's answer, using some inspiration from another answer (that I can't find right now, apologies to its author).

It seems that because of the new ESM format of this module, jest really has trouble with. I'm using Jest, ESM, Typescript, babel-jest, React, and whatever other latest modules there are as of the time of this post.

Here's what I came up with (below), which allows the tests to run cleanly. You must set up the transformIgnorePatterns to ignore not only react-markdown but all of its dependencies, and update them whenever react-markdown updates its own dependencies. So I've compiled them all into an array that's joined up and inserted into the RegEx for the ignore patterns to make this easier to read.

You don't need to stub-out react-markdown using moduleNameMapper or anything like that. And don't bother trying to remap react-markdown/react-markdown.min.js either, as v9.x doesn't include a CommonJS fallback any more.

const esModules = [
  /** react-markdown 9.0.1 */
  'react-markdown',
  'bail',
  'comma-separated-tokens',
  'decode-named-character-reference',
  'devlop/lib/default',
  'estree-util-is-identifier-name',
  'hast-util-.*',
  'html-url-attributes',
  'is-plain-obj',
  'mdast-util-.*',
  'micromark.*',
  'property-information',
  'remark-.*',
  'space-separated-tokens',
  'trim-lines',
  'trough',
  'unified',
  'unist-.*',
  'vfile-message',
  /** react-markdown 8.0.3 */
  'vfile',
].join('|')

// In the config:
{
  ...
  transformIgnorePatterns: [
    // Enable babel transforms for these specific packages. They ship code as es
    // modules only, and must be transpiled in order to run on Node.
    `[/\\\\]node_modules[/\\\\](?!${esModules}).+\\.(js|jsx|mjs|cjs|ts|tsx)$`,
  ],
  ...
}
Astaire answered 17/7, 2024 at 17:44 Comment(0)
C
0

To workaround this issue in v9+ we created a mock that still allowed us to verify that the content passed to ReactMarkdown was rendered to the screen (Note: example code is in Typescript).

import { ReactNode } from "react";

interface ChildrenProps {
    children: ReactNode;
}

function ReactMarkdownMock({ children }: ChildrenProps) {
    return <p>{children}</p>;
}

export default ReactMarkdownMock;

This was then registered in jest.config.js:

…
moduleNameMapper: {
  'react-markdown': '"<rootDir>/mock/ReactMarkdownMock.tsx',
},
…
Cabe answered 26/7, 2024 at 16:9 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.