'Jest encountered an unexpected token with react + konva and/or react-konva
With Konva and react-konva installed and imported, my jest@enzyme tests failed to run with this error:
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Details:
C:\avius\fortest\node_modules\konva\lib\Core.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export { Konva } from './_CoreInternals.js';
^^^^^^
SyntaxError: Unexpected token 'export'
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
at Object.<anonymous> (node_modules/react-konva/lib/ReactKonvaCore.js:19:13)
it is a newly created create-react-app for testing this error, so there is nothing special in it. I have no babel.rc, nor babel.config.js or jest.config.js file. (because I tried a lot of setting, does not work.)
I can import and use other es6 modules like nanoid, lodash etc, so it seems that the konva needs something special? Uninstalling konva, everything working fine.
Solution 1:[1]
To get this to work I did the following:
I created a .babelrc containing the following:
{
"presets": [
"@babel/preset-react"
],
"plugins": [
"@babel/plugin-transform-modules-commonjs"
]
}
This makes sure the files are in the correct format. You will also have to install those packages.
I then put the following within my package.json file:
"jest": {
"testEnvironment":"jsdom",
"moduleNameMapper": {
"^konva": "konva/konva"
}
}
For good measure, I reinstalled all of my react-konva files (though that shouldn't have made a difference).
Extra:
If you get issues about not having certain variables defined make sure you have konva and canvas installed.
Solution 2:[2]
I was facing the same issue when I was using react-konva + react testing + react-jest-dom . What I observed , I got react-konva and react-jest-dom versions are not supporting each other. I uninstalled react-jest-dom and then again installed it. it worked for me. you can try this if the error is something like Jest encountered an unexpected token with react + konva and/or react-konva or export react-konva.
Solution 3:[3]
This happend to me while upgrading from react 16 to 17. this suggestion worked for me https://www.gitmemory.com/issue/konvajs/konva/1168/921810056
package.json
"jest": {
"moduleNameMapper": {
"^konva": "konva/konva"
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | luwy |
