Babel unexpected token import when running mocha tests
It seems the only solution is to explicitly include:
require('babel-core/register')({
ignore: /node_modules/(?!ProjectB)/
});
in a test helper file, and pass that along to mocha in my test command:
mocha --require ./test/testHelper.js...
The final solution:
Add registerBabel.js: a separate file whose job is to require babel-core/register...
require('babel-core/register')({
ignore: /node_modules/(?!ProjectB)/
});
Add an entry.js if your application also relies on babel-node. This acts as a wrapper for your es6 containing application.
require('./registerBabel');
require('./server'); // this file has some es6 imports
You would then run your application with node entry
For mocha testing, testHelper.js should require registerBabel.js as well to initialize babel support at run time.
require('./registerBabel');
And run your mocha tests with mocha --require ./testHelper.js '+(test)/**/*Spec.js'
This will recursively test any file ending in "Spec.js" within "./test". Substitute the pattern with one matching the specs in your project.
For Babel <6
The easiest way to solve this problem is:
npm install babel-preset-es2015 --save-dev
Add
.babelrc
to the root of the project with contents:{ "presets": [ "es2015" ] }
Ensure that you are running mocha with the "--compilers js:babel-core/register" parameter.
For Babel6/7+
npm install @babel/preset-env --save-dev
Add
.babelrc
to the root of the project with contents:{ "presets": [ "@babel/preset-env" ] }
Ensure that you are running mocha with the --compilers js:babel-register
(Babel 6) or --compilers js:@babel/register
(Babel 7) parameter
For mocha version 7 or later, use --require babel-register
or --require @babel/register
respectively.