Gross unexpected token import while performing mocha tests

My project has already implemented the solutions proposed in other related issues, such as the inclusion of the corresponding presets (es2015) in .babelrc.

I have two projects (you can call them A and B) that use the ES6 module syntax. In Project A, I import Project B, which is installed through npm and lives in the node_modules folder. When I run my test suite for Project A, I get an error message:

SyntaxError: unexpected token import

preceded by this alleged erroneous line of code from project B:

(function (export, require, module, __filename, __dirname) {import createBrowserHistory from 'history / lib / createBrowserHistory';

iife seems to be something of npm or possibly babel as my source file contains only “import createBrowserHistory from“ history / lib / createBrowserHistory ”; the unit tests in the Project B test suite run fine and if I remove Project B as a dependency on project A, my test suite then (still using es6 import for internal project modules) works fine.

Full stack trace:

SyntaxError: Unexpected token import at exports.runInThisContext (vm.js:53:16) at Module._compile (module.js:374:25) at Module._extensions..js (module.js:405:10) at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:138:7) at Module.load (module.js:344:32) at Function.Module._load (module.js:301:12) at Module.require (module.js:354:17) at require (internal/module.js:12:17) at Object.<anonymous> (actionCreators.js:4:17) at Module._compile (module.js:398:26) at loader (/ProjectA/node_modules/babel-register/lib/node.js:130:5) at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:140:7) at Module.load (module.js:344:32) at Function.Module._load (module.js:301:12) at Module.require (module.js:354:17) at require (internal/module.js:12:17) at Object.<anonymous> (/ProjectA/src/components/core/wrapper/wrapper.js:28:23) at Module._compile (module.js:398:26) at loader (/ProjectA/node_modules/babel-register/lib/node.js:130:5) at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:140:7) at Module.load (module.js:344:32) at Function.Module._load (module.js:301:12) at Module.require (module.js:354:17) at require (internal/module.js:12:17) at Object.<anonymous> (/ProjectA/src/components/core/wrapper/wrapperSpec.js:15:16) at Module._compile (module.js:398:26) at loader (/ProjectA/node_modules/babel-register/lib/node.js:130:5) at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:140:7) at Module.load (module.js:344:32) at Function.Module._load (module.js:301:12) at Module.require (module.js:354:17) at require (internal/module.js:12:17) at /ProjectA/node_modules/mocha/lib/mocha.js:219:27 at Array.forEach (native) at Mocha.loadFiles (/ProjectA/node_modules/mocha/lib/mocha.js:216:14) at Mocha.run (/ProjectA/node_modules/mocha/lib/mocha.js:468:10) at Object.<anonymous> (/ProjectA/node_modules/mocha/bin/_mocha:403:18) at Module._compile (module.js:398:26) at Object.Module._extensions..js (module.js:405:10) at Module.load (module.js:344:32) at Function.Module._load (module.js:301:12) at Function.Module.runMain (module.js:430:10) at startup (node.js:141:18) at node.js:980:3 

Here is my test command from package.json:

 "test": "mocha --compilers js:babel-core/register '+(test|src)/**/*Spec.js'" 

This StackOverflow entry is similar, but does not offer a solution for my command line: import module from node_modules with babel, but failed

+78
npm babeljs syntax-error mocha
Jan 27 '16 at 15:09
source share
17 answers

It seems the only solution is to explicitly include:

 require('babel-core/register')({ ignore: /node_modules/(?!ProjectB)/ }); 

in the helper test file and pass it mocha in my test command:

 mocha --require ./test/testHelper.js... 



Final decision:

Add registerBabel.js : a separate file that requires babel-core / register ...

 require('babel-core/register')({ ignore: /node_modules/(?!ProjectB)/ }); 

Add entry.js if your application also uses babel-node. This acts as a wrapper for your application containing es6.

 require('./registerBabel'); require('./server'); // this file has some es6 imports 

Then you start your application with node entry

For testing mocha, testHelper.js should also require registerBabel.js to initialize babel support at run time.

 require('./registerBabel'); 

And run your mocha tests with mocha mocha --require./testHelper.js '+(test)/**/*Spec.js'

This will recursively check any file ending with "Spec.js" within "./test". Replace the template with one that matches the specifications of your project.

+44
Jan 27 '16 at 18:15
source share

For Babylon <6

The easiest way to solve this problem:

  1. npm install babel-preset-es2015 --save-dev
  2. Add .babelrc to the project root with the contents:

     { "presets": [ "es2015" ] } 

Make sure you run mocha with the option "--compilers js: babel-core / register".

For Babel6 / 7 +

  1. npm install @babel/preset-env --save-dev
  2. Add .babelrc to the project root with the contents:

     { "presets": [ "@babel/preset-env" ] } 

Make sure you use mocha with the option --compilers js:babel-register (Babel 6) or --compilers js:@babel/register (Babel 7)

+72
May 6 '16 at 16:08
source share

I am sure that you will have this problem, you are using ES6, that Mocha does not know

So you are using babel but not using it in your test ...

A few solutions:

but. if you use NPM use

"test": "mocha --compilers js:babel-core/register test*.js"

B. I use

"test": "./node_modules/.bin/mocha --compilers js:babel-core/register **/*spec.jsx"

C. From cli:

mocha --compilers js: babel-core / register test * .js

You can read more at http://www.pauleveritt.org/articles/pylyglot/es6_imports/

+26
Jul 21 '16 at 21:56
source share

I ran into the same problem. Having tried any other solution in stackoverflow and beyond, adding this simple configuration to package.json, I did this for me:

  "babel": { "presets": [ "es2015" ] } 

After that, all my ES6 imports worked. By the way, I had the same configuration inside webpack.config.js, but, apparently, this was the only way to make it work for mocha testing.

Hope this helps someone.

+23
Jul 03 '16 at 19:23
source share

I had {"modules": false} in my .babelrc file, for example:

 "presets": [ ["es2015", {"modules": false}], "stage-2", "react" ] 

who threw

Unexpected Token Import

As soon as I removed it, the mocha worked successfully.

+14
Mar 16 '17 at 12:31 on
source share

I had the same problem and fixed it by reading from the documentation for babel for integrating Babel with Mocha:

 { "scripts": { "test": "mocha --compilers js:babel-register" } } 
+8
Jul 05 '17 at 14:22
source share

For those using Babel 7 and Mocha 4, some package names have changed slightly, and the accepted answer is a bit outdated. What I had to do:

npm install @babel/register --saveDev

and add --require @babel/register to the test line in package.json

"test": "./node_modules/mocha/bin/mocha --require @babel/polyfill --require @babel/register './test/**/*.spec.js'"

@babel/polyfill fixes some things like async / await if you use them.

Hope this helps someone :)

+3
Oct 06 '18 at 3:29
source share

I found the easiest way to do with babel 6.XX was to use nyc and then add the helper file to pckage.json

So here is what I used

package.json

 { .... "scripts": { "test": "nyc mocha --reporter tap 'test/**/*.spec.js'" }, "devDependencies": { "babel-cli": "^6.24.0", "babel-core": "^6.24.0", "babel-loader": "^6.4.0", "babel-preset-env": "^1.2.2", "babel-preset-es2015": "^6.24.0", "babel-preset-react": "^6.23.0", "babel-preset-react-hmre": "^1.1.1", "babel-preset-stage-2": "^6.22.0", "babel-register": "^6.24.0", "babel-runtime": "^6.23.0", "chai": "^3.5.0", "mocha": "^3.2.0", "nyc": "^10.1.2", "webpack": "^2.3.3", "webpack-config": "^7.0.0", "webpack-dashboard": "^0.3.0", "webpack-dev-server": "^2.4.2" }, "nyc": { "all": true, "include": [ "src/**/*.js" ], "cache": true, "require": [ "./test/helper/registerBabel.js" ] } } 

babelrc

 { "presets": [ "es2015", //remove the {modules: false} it doesn't work with this "stage-2" ] } 

registerBabel.js

 /* eslint-disable import/no-commonjs, import/unambiguous */ require('babel-register')(); 

Now you can use es6 in your tests or wherever you need. Mines all fail;)

Then npm run test , which will disable nyc mocha --reporter tap 'test/**/*.spec.js'

+2
Apr 05 '17 at 11:55 on
source share

--compilers deprecated.

My simple solution:

 npm install --save-dev babel-core 

And in package.json add your test script as follows:

  "scripts": { "test": "mocha --require babel-core/register ./test/**/*.js -r ./test-setup.js" }, 
+2
Dec 02 '17 at 2:38 on
source share

This is what worked for me. I got a warning when using the --compilers flag.

Deprecation warning: "--compilers" will be removed in a future version of Mocha; see https://git.io/vdcSr for more information

So I replaced it with the --require flag

 "test": "mocha --require babel-core/register --recursive" 

Here is my .babelrc :

 { "presets": ["env"] } 

My dependencies for package.json dev

 "devDependencies": { "babel-cli": "^6.26.0", "babel-preset-env": "^1.7.0", "mocha": "^5.2.0", } 
+2
Sep 28 '18 at 9:27
source share

You may need to specify the extensions option if you are using TypeScript:

 require("@babel/register")({ extensions: ['.jsx', '.js', '.ts', '.tsx'] }) 
+1
Feb 13 '19 at 19:11
source share

I solved this problem this morning with the following instructions

Install NPMs

 npm install --save-dev @babel/polyfill npm install --save-dev @babel/register 

package.json :

 "scripts": { "test": "mocha --require @babel/register --require @babel/polyfill src/DesktopApplication/Tests", } 

.babelrc

 { "presets": ["@babel/env"] } 
+1
Feb 21 '19 at 5:18
source share

I solved this problem this morning with the following official use instructions of the Babel instructions for Mocha 4:

Install NPMs

 npm install --save-dev babel-polyfill npm install --save-dev babel-preset-env npm install --save-dev babel-register 

or one command:

 npm i -d babel-polyfill babel-preset-env babel-register 

package.json

 "scripts": { "test": "mocha --require babel-polyfill --require babel-register" } 

.babelrc

 { "presets": ["env"] } 
0
Dec 13 '17 at 15:59
source share

I installed mocha and met exactly the same error when using import in my code. By following these steps, the problem has been fixed.

 npm install babel-core --save-dev npm install babel-preset-es2015 --save-dev npm install babel-preset-stage-0 --save-dev 

And then add the .babelrc file:

 { "presets": [ "es2015" ] } 

And then run mocha as follows:

 mocha --compilers js:babel-core/register 
0
Jul 27 '18 at 2:37
source share

I am adding another ES6 + mocha + babel setup answer here, current as of June 19 (see Dates in the answer / comments). --compiler flag is --compiler , and the version I use is not available even with the --no-deprecation flag, see this

Please note that I will not include all relevant snippets from the linked pages, because none of them led me to a clean test build based on the latest versions of mocha and babel; this answer should include the steps that led me to a successful test build.

Following the instructions here, and in this answer , and here , I tried to install what turned out to be the minimum latest version using npm install :

 $ npm install --save-dev mocha $ npm install --save-dev @babel/preset-env 

And I configured the mocha call in package.json like this:

 "scripts": { "test": "mocha --compilers js:@babel/register" } 

This led to errors:

 × ERROR: --compilers is DEPRECATED and no longer supported. 

As above, --no-deprecation did not help, please follow the link above. So, following the instructions from here, I configured package.json:

 "scripts": { "test": "mocha --require js:@babel/register" } 

And he began to see errors when looking for babel modules, such as:

 × ERROR: Cannot find module '@babel/register' 

At this point, I started installing babel packages until I was able to progress. I believe the full installation is something like:

 $ npm install --save-dev @babel/preset-env @babel/register @babel/core 

The latest change was to update the mocha call in package.json by removing the js: prefix js: something like this:

 "scripts": { "test": "mocha --require @babel/register" } 

I can’t answer why it was necessary: ​​if someone can answer this question, please leave a comment and I will supplement my answer with more detailed information.

The last thing I did was create .babelrc in the project directory with the contents:

{"presets": ["@ babel / preset-env"]}

I can’t remember what this caused, but I believe it was because Mocha kept complaining that he did not recognize the import keyword in my test.js. As above, if someone can answer this question, please leave a comment and I will update my answer with more details.

0
Jun 22 '19 at 23:26
source share

I had the same problem. When I ran the tests, I realized that I really wanted to block the dependent modules. It is good for unit testing and does not allow Babel to convert submodules. Therefore, I used proxyquire , namely:

 const proxyquire = require('proxyquire').noCallThru() const myTestedModule = proxyquire('../myTestedModule', { 'dependentModule1': { //stubbed module1 }, 'dependentModule2': { //stubbed module2 } }) 
-one
May 25 '16 at 9:11
source share

for more reliable installation

 npm install babel-preset-latest --save-dev 

and in .babelrc

 { "presets": [ "latest" ] } 

Unlike...

 npm install babel-preset-es2015 --save-dev 

and

 { "presets": [ "es2015" ] } 
-3
Dec 06 '16 at 18:27
source share



All Articles