React JS Jest causing "SyntaxError: Unexpected token ."

user3006967 picture user3006967 · Jan 25, 2017 · Viewed 14.5k times · Source

I am now using react JEST to test code. If a component is single, and not importing anything else, "npm test" runs smoothly, and now, I want to test multiple components together, and I immediately got this error:

SyntaxError: Unexpected token .

It seemed whenever react is importing something else, such as this one:

require( './style/fixed-data-table.css' );
require( './style/jnpr-datatable.scss' );

and then using jest is throwing the unexpected token "." error.

There must be something wrong in my settings, but where? My Package.json contains:

 "jest": {
   "unmockedModulePathPatterns": [
     "<rootDir>/node_modules/react/",
     "<rootDir>/node_modules/react-dom/",
     "<rootDir>/node_modules/react-addons-test-utils/"
   ]
 }

And the .babelrc is already in the root. Also babel-jest is included. Thanks

Answer

Andreas K&#246;berle picture Andreas Köberle · Jan 25, 2017

Have a look at the jest docs for webpack integration. The problem is that jest cant work with other stuff then js. So you have to mock all none js files you import. The easiest way is to configure a moduleNameMapper in your jest configs.

{
  "jest": {
    "moduleNameMapper": {
      "\\.(css|scss)$": "<rootDir>/__mocks__/styleMock.js"
    }
  }
}

with a __mocks__/styleMock.js that looks like this.

module.exports = {};