5

Trying to unit test reactjs application using mocha but getting error from es6 features (import/export) used inside node_modules folder. The application in question is transpiled using babel but since one of react component is using a module from node_modules its throwing error Syntax Error:Unexpected token export. I am aware that babel ignores node_modules folder by default, but not sure how to approach this. Any help would be appreciated. Thanks.

Test Command :-

  "test": "SET NODE_ENV=test&& mocha --require @babel/register --require ignore-styles -r jsdom-global/register \"./src/**/*.test.js\"",

babel.config.js :-

module.exports = function (api) {
  const presets = ["react-app"];
  const plugins = [
      "@babel/plugin-transform-modules-commonjs", 
      "inline-react-svg"
  ];
  const ignore = [/node_modules/]
  api.cache(false); 
  return {
      presets, 
      plugins,
      ignore
  }
};
Suraj A J
  • 69
  • 7

2 Answers2

1

Got it working!. Had to switch from Mocha to Jest since I was using react-app-rewired which was internally configured to use Jest. A small change in config-override.js was needed. Added a jest config with "transformIgnorePatterns": ["node_modules/(?!MODULES_TO_BE_TRANSPILED)"]. Hope it helps others.

Suraj A J
  • 69
  • 7
0

try this command, you need to pass ignored directories in command line with --ignored option.

./node_modules/.bin/babel . -d ~/app_compressed/ --ignore node_modules,test,assets,stuff,views,public,test,spec,logs,lib/jasmine_examples,db,routes/api/drafts,**/drafts

Also, make sure to use a babel.config.js file instead of a .babelrc file. so the config file will look like following.

module.exports = function (api) {
    api.cache(true);
    return {
        babelrcRoots: [
            '.',
            './modules/*'
        ],
    ignore: [/node_modules/],
    presets: ["@babel/preset-env"]
    };
}
Mahendra Pratap
  • 3,174
  • 5
  • 23
  • 45
  • Thanks for the answer. I tried --ignore option but no change. The tutorial shared is using babel-6 and I am using babel-7, so there are major changes to it isn't it? – Suraj A J Aug 01 '19 at 06:09
  • Nope, not working either. I have updated question to show babel changes. Please check. Also I am facing error when trying to run mocha test command. Your answer suggests babel command. Can you please confirm? Please check my question for mocha test command being run. – Suraj A J Aug 01 '19 at 06:52
  • well, it is confusing. I have updated my answer with my babel.config.js file and it is working. – Mahendra Pratap Aug 01 '19 at 07:06