Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error importing component in Jest tests with TypeScript #635

Closed
4 tasks done
tubbo opened this issue Aug 17, 2021 · 22 comments
Closed
4 tasks done

Error importing component in Jest tests with TypeScript #635

tubbo opened this issue Aug 17, 2021 · 22 comments
Labels
🙋 no/question This does not need any changes 👎 phase/no Post cannot or will not be acted on

Comments

@tubbo
Copy link

tubbo commented Aug 17, 2021

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)

@github-actions github-actions bot added 👋 phase/new Post is being triaged automatically 🤞 phase/open Post is being triaged manually and removed 👋 phase/new Post is being triaged automatically labels Aug 17, 2021
@ChristianMurphy
Copy link
Member

ChristianMurphy commented Aug 17, 2021

As part of the the version 7 release, the react-markdown is packaged as standard ESM.
Despite ESM being standard for JavaScript, some tools, including Jest and Electron require some configuration to use ESM.
https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c documents how ESM can be used with Jest and Electron, and many other tools as well.

Happy to discuss more at https://github.com/remarkjs/remark/discussions on approaches to resolve.
This isn't a bug/pain-point specific to react-markdown so much as a bug/pain-point with Jest.

@ChristianMurphy ChristianMurphy added 🙋 no/question This does not need any changes and removed 🤞 phase/open Post is being triaged manually labels Aug 17, 2021
@github-actions

This comment has been minimized.

@github-actions github-actions bot added the 👎 phase/no Post cannot or will not be acted on label Aug 17, 2021
@tubbo
Copy link
Author

tubbo commented Aug 18, 2021

Thanks for the response Christian! I didn't realize discussions were enabled on this repo, will move this to a discussion since I agree with you that this isn't really a problem with any one tool in particular..

@nvh95
Copy link

nvh95 commented Nov 1, 2021

(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)$',
  ],
...
};

@larsnystrom
Copy link

Option 3 descibed by nvh95 above does not work, probably due to bug jestjs/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"
  },
}

@mikegoatly
Copy link

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", () => () => {
})

@illume
Copy link

illume commented Jan 20, 2022

option 3 from #635 (comment) by @nvh95 and mentioned in the jest docs worked for me. Makes the test runtime quite a bit slower to run though. Note: It did used to work before upgrading to CRA 5 with webpack 5.

@juanmartinez-viamericas
Copy link

juanmartinez-viamericas commented Mar 28, 2022

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',
  },
};

@lamai6
Copy link

lamai6 commented Apr 3, 2022

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"
  }
}

@talentedandrew

This comment was marked as duplicate.

@matttk
Copy link

matttk commented Jul 19, 2022

FYI: Option 3 isn't working for me after I updated a lot of minor versions of packages but I switched to the method of mocking react-markdown and that works no problem.

@nvh95
Copy link

nvh95 commented Aug 19, 2022

@matttk I just check that react-markdown add a new ESM-only dependency trim-lines, so I updated option 3 to make it work in Jest.

To others: If option 3 does not work in the future. Please mention me, I will update the dependency :)

@AntonioDev152
Copy link

I hope this helps
jest.mock('react-markdown', () => { return ({ children }) => { return children } })

@Beef-Boy
Copy link

(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 solved this using Option 1 in a CRA typescript project.

cmil added a commit to dracor-org/einakter that referenced this issue Sep 28, 2022
We need to mock reac-markdown and react-leaflet since jest does not
fully support ESM syntax yet. See
remarkjs/react-markdown#635 (comment).
@fbruckhoff
Copy link

To others: If option 3 does not work in the future. Please mention me, I will update the dependency :)

@nvh95 This didn't work for me. Can you confirm what the latest required config would look like, if you wanted to test a component that uses react-markdown 🙂

@kokanmale-db
Copy link

@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',
];

@gabrielmlinassi
Copy link

gabrielmlinassi commented Dec 31, 2022

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

@gsouf
Copy link

gsouf commented Apr 4, 2023

Anyone has an idea how to get it to work with Mocha without specifying `"type": "module"?

@RachelElysia
Copy link

RachelElysia commented Jun 2, 2023

If anyone's still struggling with getting their ${esModules} to work on jest.config.ts, make sure that your babel.config.json is not named .babel.rc. For whatever reason that prevents nvh95's solution that ended up working once changing the name of .babel.rc.

nvh95's solution: #635 (comment)
source that .babel.rc didn't play nicely: jestjs/jest#11067 (comment)

@weyert
Copy link

weyert commented Sep 6, 2023

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

@djanowski
Copy link

A take on this solution that doesn't require you to list every module to be transformed and rather finds them automatically:

async function jestConfig() {
  const modules = await fs.readdir("node_modules");
  let esModules = [];

  for (const m of modules) {
    try {
      await import(m);
    } catch (error) {
      esModules.push(m);
    }
  }

  const esModulesPattern = esModules.join("|");
  const nextJestConfig = await createJestConfig(config)();
  nextJestConfig.transformIgnorePatterns[0] = `/node_modules/(?!${esModulesPattern}).+.(js|jsx|mjs|cjs|ts|tsx)$/`;

  return nextJestConfig;
}

@crhuff-ibm
Copy link

I know this is an old issue, but just to throw some additional debugging in for anyone like me.

I have a component library that uses ReactMarkdown, and within our products that consume the library we use CJS/jest to test our code. In this situation, I continued to get the issue even after mocking react-markdown.js. This threw the following error

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

The solution is to mock the package so that it is CJS compatible, which is as follows:

const ReactMarkdown = ({ children }) => children;

module.exports = ReactMarkdown; // module.exports instead of export default

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🙋 no/question This does not need any changes 👎 phase/no Post cannot or will not be acted on
Development

No branches or pull requests