Search code examples
reactjsjestjsreactjs-testutils

Why Jest is throwing "Unexpected token ILLEGAL" when testing React component?


I followed the Jest - React tutorial to test a React component.

Unfortunately, Jest throws:

SyntaxError: /Users/mishamoroshko/react-playground/src/search-panel/questions/__tests__/questions-test.js: /Users/mishamoroshko/react-playground/src/search-panel/questions/questions.js: Unexpected token ILLEGAL
at Contextify.sandbox.run (/Users/mishamoroshko/react-playground/node_modules/jest-cli/node_modules/jsdom/node_modules/contextify/lib/contextify.js:12:24)
at JSDomEnvironment.runSourceText (/Users/mishamoroshko/react-playground/node_modules/jest-cli/src/JSDomEnvironment.js:108:22)
at Object.runContentWithLocalBindings (/Users/mishamoroshko/react-playground/node_modules/jest-cli/src/lib/utils.js:341:23)

To reproduce:

  1. git clone [email protected]:SEEK-Jobs/react-playground.git
  2. cd react-playground
  3. npm install
  4. npm test

Any ideas?


UPDATE 1:

I wonder whether the problem is that Jest doesn't know about ES6, and I need to use 6to5-jest.

Is there a way to specify 2 preprocessors in package.json?

"jest": {
  "rootDir": "src",
  "scriptPreprocessor": "../preprocessor.js",
  "unmockedModulePathPatterns": [
    "../node_modules/react"
  ]
}

Solution

  • Indeed, adding 6to5-jest solved the problem.

    Here is how I implemented multiple scriptPreprocessors in Jest:

    // preprocessor.js
    
    var ReactTools = require('react-tools');
    var to5 = require('6to5-jest').process;
    
    module.exports = {
      process: function(src, filename) {
        return ReactTools.transform(to5(src, filename));
      }
    };
    

    If you have a better way to implement this, please leave a comment.