-
-
Notifications
You must be signed in to change notification settings - Fork 876
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
Comments
As part of the the version 7 release, the Happy to discuss more at https://github.com/remarkjs/remark/discussions on approaches to resolve. |
This comment has been minimized.
This comment has been minimized.
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)
// src/__mocks__/react-markdown.js
function ReactMarkdown({ children }){
return <>{children}</>;
}
export default ReactMarkdown; You lose the ability to actually test the
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
Update Aug 19, 2022: Add dependency "trim-lines" // 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
|
I ended up using jest.mock("react-markdown", () => (props) => {
return <>{props.children}</>
})
jest.mock("remark-gfm", () => () => {
}) |
…en 'export' https://app.circleci.com/pipelines/github/ademidun/atila-client-web-app/1772/workflows/ff5de33e-07e3-416b-af65-d01c488818b2/jobs/3343 see: remarkjs/react-markdown#635 (comment) Details: /home/circleci/repository/node_modules/react-markdown/index.js:6 export {uriTransformer} from './lib/uri-transformer.js' ^^^^^^ SyntaxError: Unexpected token 'export' 1 | import React from 'react' > 2 | import ReactMarkdown from 'react-markdown';
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.
import React from 'react';
function ReactMarkdown({ children }){
return <>{children}</>;
}
export default ReactMarkdown;
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"
}
} |
This comment was marked as duplicate.
This comment was marked as duplicate.
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 |
@matttk I just check that To others: If option 3 does not work in the future. Please mention me, I will update the dependency :) |
I hope this helps |
I solved this using Option 1 in a CRA typescript project. |
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 Here is a list that worked for me with the latest
|
For whom is looking for a solution that works with Nextjs, notice 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 nvh95's solution: #635 (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
The solution is to mock the package so that it is CJS compatible, which is as follows:
|
Creating a ReactMarkdown component in /tests/mocks/react-markdown.js file and exporting it in module.exports = { /tests/mocks/react-markdown.js file import React from 'react'; export default ReactMarkdown; Solved my issue. |
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 configuretransformIgnorePatterns
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
Runtime
Node v14
Package manager
yarn v2
OS
macOS
Build and bundle tools
Webpack, Other (please specify in steps to reproduce)
The text was updated successfully, but these errors were encountered: