jsoneditor-react icon indicating copy to clipboard operation
jsoneditor-react copied to clipboard

Unable to run Jest tests when running under create-react-app

Open lepinkainen opened this issue 4 years ago • 6 comments

When trying to run Jest tests under create react app with yarn test I get the following error:

  ● Test suite failed to run

    /projects/project/node_modules/jsoneditor-react/es/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import React, { Component } from 'react';
                                                                                             ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      2 | import { Button, Col, Row, Container } from "reactstrap";
      3 |
    > 4 | import { JsonEditor as Editor } from "jsoneditor-react";
        | ^
      5 | import "jsoneditor-react/es/editor.min.css";
      6 |

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)

The code compiles just fine without any errors and works as intended. Somehow running it with NODE_ENV=test causes the transpiler to fail.

lepinkainen avatar May 25 '20 12:05 lepinkainen

you need to provide correct transformer to jest, see https://jestjs.io/docs/en/getting-started#using-babel

vankop avatar May 25 '20 13:05 vankop

It's a bit of a pain to edit the babel settings in a CRA based project without ejecting it.

Any hints on what are the correct transformers to make it work in a CRA TypeScript project? Or why this error is thrown during testing, but not when compiling?

lepinkainen avatar May 25 '20 21:05 lepinkainen

@lepinkainen if you will create reproduction repo I could take a look. As I understand you can override options https://create-react-app.dev/docs/running-tests#configuration you need to allow jsoneditor-react https://jestjs.io/docs/en/configuration#transformignorepatterns-arraystring

vankop avatar May 25 '20 22:05 vankop

transformIgnorePatterns did not work for me.

Had to use: moduleNameMapper: { "jsoneditor-react": a file with empty stub }

alicialics avatar Jul 08 '20 07:07 alicialics

@alicialics Can you share the stub file you used?

lepinkainen avatar May 19 '21 11:05 lepinkainen

@lepinkainen here's what I used:

package.json:

  "jest": {
    "moduleNameMapper": {
      "jsoneditor-react": "<rootDir>/src/stub.js"
    }
  },

stub.js:

var Editor = function() {};
export { Editor as JsonEditor };

bruderda avatar Jun 10 '21 21:06 bruderda