5

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.

2 Answers2

0

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.

Oliver Brace
  • 393
  • 1
  • 4
  • 21
  • Also if you encounter a `Cannot read property 'autoDrawEnabled' of undefined` there is an issue in for it: https://github.com/konvajs/react-konva/issues/630 – Oliver Brace Nov 19 '21 at 09:50
0

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.