react-markdown: Error importing component in Jest tests with TypeScript

Initial checklist

Affected packages and versions

react-markdown@npm:7.0.0 [bad77] (via npm:^7.0.0 [bad77])

Link to runnable example

https://github.com/tubbo/react-markdown-repro

Steps to reproduce

Install react-markdown on a TypeScript project and try to use it in a test. I used CRA in my example but that isn’t strictly necessary, as I came across the issue on an Electron project. Trying to configure transformIgnorePatterns to whitelist this module also proves impossible, as you have to also whitelist every dependency of the module which is a nightmare.

Expected behavior

Test should run without having trouble importing the file

Actual behavior

 FAIL  src/community/community.test.tsx
  ● 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.
     • 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:

    /[...]/node_modules/react-markdown/index.js:5
    import { ReactMarkdown } from './lib/react-markdown.js';
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

    > 1 | import ReactMarkdown from 'react-markdown'

Runtime

Node v14

Package manager

yarn v2

OS

macOS

Build and bundle tools

Webpack, Other (please specify in steps to reproduce)

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 12
  • Comments: 21 (1 by maintainers)

Commits related to this issue

Most upvoted comments

(For folks who are googling after installing and cannot run jest) Since Jest has not fully supported ESM yet. So to make react-markdown work in jest, other than opt-in for ESM in jest, you guys can use one of following options (solutions tested with Create React App 4.0.3):

  • Option 1: mock react-markdown
// src/__mocks__/react-markdown.js
function ReactMarkdown({ children }){
  return <>{children}</>;
}

export default ReactMarkdown;

You lose the ability to actually test the react-markdown package but the troublesome is now gone.

  • Option 2: Downgrade to react-markdown version 6

Since version 6 shipped with CommonJS build so it should be no problem working with Jest. This is easiest solution but not recommended. You can upgrade to newer version when jest fully support ESM or react-markdown bundles CommonJS (not likely to happen).

Update Aug 19, 2022: Add dependency “trim-lines” Update Nov 1, 2021: Add more dependencies, thanks to @lamai6

// jest.config.js
// move "jest" config from `package.json` to `jest.config.js`
const esModules = [ // Copy from here 👈
  "react-markdown",
  "vfile",
  "unist-.+",
  "unified",
  "bail",
  "is-plain-obj",
  "trough",
  "remark-.+",
  "mdast-util-.+",
  "micromark",
  "parse-entities",
  "character-entities",
  "property-information",
  "comma-separated-tokens",
  "hast-util-whitespace",
  "remark-.+",
  "space-separated-tokens",
  "decode-named-character-reference",
  "ccount",
  "escape-string-regexp",
  "markdown-table",
  "trim-lines",
].join("|"); // To here 👈

module.exports = {
...
transform: {
    '^.+\\.(js|jsx|mjs|cjs|ts|tsx)$': '<rootDir>/config/jest/babelTransform.js',
    [`(${esModules}).+\\.js$`]: '<rootDir>/config/jest/babelTransform.js', // Add this line 👈
    '^.+\\.css$': '<rootDir>/config/jest/cssTransform.js',
    '^(?!.*\\.(js|jsx|mjs|cjs|ts|tsx|css|json)$)':
      '<rootDir>/config/jest/fileTransform.js',
  },
  transformIgnorePatterns: [
//   Update from this 👈
//  "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs|cjs|ts|tsx)$", 
    `[/\\\\]node_modules[/\\\\](?!${esModules}).+\\.(js|jsx|mjs|cjs|ts|tsx)$`, // To this 👈
    '^.+\\.module\\.(css|sass|scss)$',
  ],
...
};

I ended up using jest.mock in my setupTests.js to mock out both react-select and remark-gfm:

jest.mock("react-markdown", () => (props) => {
    return <>{props.children}</>
})

jest.mock("remark-gfm", () => () => {
})

I’ve joined the answers from @mvh25 and @mikegoatly, and works like a charm.

  1. Create a file: __test__/__mocks__/react-markdown.js
import React from 'react';

function ReactMarkdown({ children }){
  return <>{children}</>;
}

export default ReactMarkdown;
  1. On jest.config.js file add:
module.exports = {
  moduleNameMapper: {
    'react-markdown': '<rootDir>/__test__/mocks/react-markdown.js',
  },
};

Option 3 descibed by nvh95 above does not work, probably due to bug facebook/jest#11067 . So unless you want to downgrade to react-markdown 6, the only option is to mock react-markdown during testing. nvh95 described how above, but in addition to that I also had to add

// jest.config.js
{
  // ...
  moduleNameMapper: {
    "react-markdown": "<rootDir>/resources/mocks/react-markdown.js"
  },
}

Doesn’t seem to work anymore with Next.js 13 for me

Option 3 from this #635 comment still works but needs an update, as other dependencies have been added since the comment.

Solution

// jest.config.js

const esModules = [
  'react-markdown',
  'vfile',
  'unist-.+',
  'unified',
  'bail',
  'is-plain-obj',
  'trough',
  'remark-.+',
  'mdast-util-.+',
  'micromark',
  'parse-entities',
  'character-entities',
  'property-information',
  'comma-separated-tokens',
  'hast-util-whitespace',
  'remark-.+',
  'space-separated-tokens',
  'decode-named-character-reference',
  'ccount',
  'escape-string-regexp',
  'markdown-table',
].join('|');

module.exports = {
  moduleNameMapper: {
    // ...
  },
  testEnvironment: 'jest-environment-jsdom',
  transform: {
    '\\.[jt]sx?$': 'babel-jest',
  },
  transformIgnorePatterns: [
    `[/\\\\]node_modules[/\\\\](?!${esModules}).+\\.(js|jsx|mjs|cjs|ts|tsx)$`,
  ],
};

Environment

{
  "engines": {
    "node": "16.14.0",
    "npm": "8.3.1"
  },
  "someDependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-markdown": "^8.0.2",
    "remark-gfm": "^3.0.1"
  },
  "someDevDependencies": {
    "@babel/cli": "^7.17.6",
    "@babel/core": "^7.17.5",
    "@babel/preset-env": "^7.16.11",
    "@testing-library/jest-dom": "^5.16.2",
    "@testing-library/react": "^12.1.4",
    "babel-loader": "^8.2.3",
    "jest": "^27.5.1"
  }
}

For whom is looking for a solution that works with Nextjs, notice transformIgnorePatterns doesn’t work the same way in NextJS due to how next/jest is implemented. More details here. This solution worked for me.

async function jestConfig() {
  const nextJestConfig = await createJestConfig(customJestConfig)()
  nextJestConfig.transformIgnorePatterns[0] = `/node_modules/(?!${esModules}).+.(js|jsx|mjs|cjs|ts|tsx)$`
  return nextJestConfig
}

module.exports = jestConfig

@fbruckhoff Here is a list that worked for me with the latest react-markdown version

const esModules = [
  'react-markdown',
  'vfile.*',
  'unist-.+',
  'rehype.*',
  'unified',
  'bail',
  'is-.+',
  'trough',
  'remark-.+',
  'mdast-util-.+',
  'micromark.*',
  'parse-entities',
  'character-entities',
  'property-information',
  'comma-separated-tokens',
  'hast-.+',
  'hastscript',
  'space-separated-tokens',
  'decode-named-character-reference',
  'ccount',
  'escape-string-regexp',
  'markdown-table',
  'trim-lines',
  'web-namespaces',
  'zwitch',
  'html-void-elements',
  'github-slugger',
  'refractor',
  'character-.+',
  'direction',
  'bcp-47-match',
  'stringify-entities',
];