Error importing component in Jest tests with TypeScript
tubbo opened this issue · 22 comments
Initial checklist
- I read the support docs
- I read the contributing guide
- I agree to follow the code of conduct
- I searched issues and couldn’t find anything (or linked relevant results below)
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)
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.
Hi team! I don’t know what’s up as there’s no phase label. Please add one so I know where it’s at.
Thanks,
— bb
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..
(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).
- Option 3: If you still want to make jest run react-markdown's code. Transform react-markdown (and its dependencies) using
babel-jest
(solution for CRA 4.0.3) (credit to nrwl/nx#812 (comment))
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)$',
],
...
};
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"
},
}
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", () => () => {
})
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.
I've joined the answers from @MVH25 and @mikegoatly, and works like a charm.
- Create a file:
__test__/__mocks__/react-markdown.js
import React from 'react';
function ReactMarkdown({ children }){
return <>{children}</>;
}
export default ReactMarkdown;
- On
jest.config.js
file add:
module.exports = {
moduleNameMapper: {
'react-markdown': '<rootDir>/__test__/mocks/react-markdown.js',
},
};
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"
}
}
Option 3 from #635 (comment) worked for me. But needs some update.
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',
'hast-util-.+',
'escape-string-regexp',
'markdown-table',
'rehype-.+',
'hastscript',
'web-namespaces',
'hast-.+',
'zwitch',
'html-void-elements'
].join('|');
module.exports = {
testEnvironment: "jsdom",
transform: {
'^.+\\.(js|jsx|mjs|cjs|ts|tsx)$': 'babel-jest',
[`(${esModules}).+\\.js$`]: 'babel-jest',
},
transformIgnorePatterns: [`[/\\\\]node_modules[/\\\\](?!${esModules}).+\\.(js|jsx|mjs|cjs|ts|tsx)$`,
'^.+\\.module\\.(css|sass|scss)$'],
};
babel.config.js
module.exports = {
presets: [
"@babel/preset-env",
"@babel/preset-react",
"@babel/preset-typescript",
],
plugins: ["@babel/plugin-transform-modules-commonjs"]
};
package.json
"peerDependencies": {
"react": "^16.0.0",
"react-dom": "^16.0.0"
},
"devDependencies": {
"@babel/core": "^7.17.8",
"@babel/plugin-transform-modules-commonjs": "^7.17.7",
"@babel/preset-env": "^7.16.11",
"@babel/preset-react": "^7.16.7",
"@babel/preset-typescript": "^7.16.7",
"@rollup/plugin-commonjs": "^21.0.3",
"@rollup/plugin-node-resolve": "^13.1.3",
"@rollup/plugin-typescript": "^8.3.1",
"@testing-library/react": "^12.1.2",
"@types/jest": "^27.4.1",
"@types/react": "^17.0.43",
"babel-jest": "^27.5.1",
"jest": "^27.5.1",
"rollup": "^2.70.1",
"rollup-plugin-dts": "^4.2.0",
"rollup-plugin-peer-deps-external": "^2.2.4",
"rollup-plugin-terser": "^7.0.2",
"tslib": "^2.3.1",
"typescript": "^4.6.3"
},
"dependencies": {
"react-markdown": "^8.0.2",
"rehype-raw": "^6.1.1",
"remark-gfm": "^3.0.1"
}
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.
@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 :)
I hope this helps
jest.mock('react-markdown', () => { return ({ children }) => { return children } })
(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 6Since 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).
- Option 3: If you still want to make jest run react-markdown's code. Transform react-markdown (and its dependencies) using
babel-jest
(solution for CRA 4.0.3) (credit to How to set transformIgnorePatterns to fix "Jest encountered an unexpected token" nrwl/nx#812 (comment))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.
@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',
];
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
Anyone has an idea how to get it to work with Mocha without specifying `"type": "module"?
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)
Doesn't seem to work anymore with Next.js 13 for me
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;
}
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