ThinkingInBits
ThinkingInBits

Reputation: 11482

Babel unexpected token import when running mocha tests

The solutions offered in other related questions, such as including the proper presets (es2015) in .babelrc, are already implemented in my project.

I have two projects (lets call them A and B) which both use ES6 module syntax. In Project A, I'm importing Project B which is installed via npm and lives in the node_modules folder. When I run my test suite for Project A, I'm getting the error:

SyntaxError: Unexpected token import

Which is preceded by this alleged erroneous line of code from Project B:

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

The iife appears to be something npm or possibly babel related since my source file only contains "import createBrowserHistory from 'history/lib/createBrowserHistory'; The unit tests in Project B's test suite runs fine, and if I remove Project B as a dependency from Project A, my test suite then (still using es6 imports for internal project modules) works just 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 post is similar but doesn't offer a solution for my use of the command line: import a module from node_modules with babel but failed

Upvotes: 98

Views: 84835

Answers (17)

Ofir Attal
Ofir Attal

Reputation: 1176

Well sure you will have that issue, you are using ES6 that mocha don't know

So you are using babel but you don't use it in your test...

Few Solutions:

A. if you running with NPM use

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

B. I'm using

"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/

Upvotes: 26

deepelement
deepelement

Reputation: 2506

For Babel <6

The easiest way to solve this problem is:

  1. npm install babel-preset-es2015 --save-dev
  2. 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+

  1. npm install @babel/preset-env --save-dev
  2. 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.

Upvotes: 85

pb2q
pb2q

Reputation: 59667

I'm adding another ES6+mocha+babel config answer here, current as of June '19 (refer to dates on answer/commente). mocha has deprecated the --compiler flag, and the version that I'm using has that unavailable even with --no-deprecation flag, c.f. this

Note that I won't include all of the relevant bits from the linked pages, because none of them got me to a clean test build based on the latest versions of mocha and babel; this answer should include the steps that got me to a successful test build.

Following the instructions here, and in this answer, and here, I tried installing what appeared to be the minimum latest babel using npm install:

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

And I adjusted the mocha invocation in package.json, like so:

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

This led to errors:

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

As above, --no-deprecation didn't help, please reference the page linked above. So following the instructions from here I adjusted package.json:

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

And started seeing errors about locating babel modules, such as:

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

At this point I started installing babel packages until I could progress. I believe that the full install is something like:

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

The last change required was to update the mocha invocation in package.json, removing the js: prefix, like so:

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

I can't answer why this was necessary: if someone can answer this please leave a comment and I'll update my answer with better information.

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

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

I can't recall what prompted this, but I believe that it was because mocha continued to complain about not recognizing the import keyword in my test.js. As above, if someone can answer this please leave a comment and I'll update my answer with better information.

Upvotes: 5

Andrey Tagaew
Andrey Tagaew

Reputation: 1603

I resolved this issue this morning with the following instructions

Install NPM Modules

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"]
}

Upvotes: 2

soundly_typed
soundly_typed

Reputation: 40396

You might need to specify the extensions option if you're using TypeScript:

require("@babel/register")({
  extensions: ['.jsx', '.js', '.ts', '.tsx']
})

Upvotes: 1

syazdani
syazdani

Reputation: 4868

For anybody using Babel 7 and Mocha 4, some of the package names have changed a bit and the accepted answer is a bit out-dated. What I had to do was:

npm install @babel/register --saveDev

and adding --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'"

The @babel/polyfill fixes some things like async/await functionality if you happen to be using those.

Hope that helps somebody :)

Upvotes: 7

productioncoder
productioncoder

Reputation: 4335

Here's what worked for me. I got a warning when using the --compilers flag.

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

I therefore replaced it with the --require flag

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

Here's my .babelrc:

{
  "presets": ["env"]
}

My package.json dev dependencies

"devDependencies": {
  "babel-cli": "^6.26.0",
  "babel-preset-env": "^1.7.0",
  "mocha": "^5.2.0",
}

Upvotes: 3

Jeff Tian
Jeff Tian

Reputation: 5923

I installed mocha and met the exact same error when I use import in my code. By doing the following actions, the issue was 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 a .babelrc file:

{
    "presets": [
        "es2015"
    ]
}

And then run mocha in this way:

mocha --compilers js:babel-core/register

Upvotes: 0

ThinkingInBits
ThinkingInBits

Reputation: 11482

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.

Upvotes: 46

Doug Wilhelm
Doug Wilhelm

Reputation: 796

I resolved this issue this morning with the following instructions from the official Using Babel instructions for Mocha 4:

Install NPM Modules

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

or a single 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"]
}

Upvotes: 1

E. Fortes
E. Fortes

Reputation: 1338

--compilers is deprecated.

My simple solution:

npm install --save-dev babel-core

And in the package.json add your test script like this:

  "scripts": {
    "test": "mocha --require babel-core/register ./test/**/*.js -r ./test-setup.js"
  },

Upvotes: 3

Ognyan Dimitrov
Ognyan Dimitrov

Reputation: 6273

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

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

Upvotes: 8

Jamie Hutber
Jamie Hutber

Reputation: 28126

I found the easiest way to do with with babel 6.X.X was to use nyc and then add in a helper file into the 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 will be able to use es6 in your tests or wherever you need to. Mine are all failing ;)

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

Upvotes: 2

JoeTidee
JoeTidee

Reputation: 26144

I had {"modules": false} in my .babelrc file, like so:

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

which was throwing

Unexpected token import

Once i removed it, mocha ran successfully.

Upvotes: 14

Phil Henry Mcboob
Phil Henry Mcboob

Reputation: 13

for a more future proof setting

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

and in .babelrc

{
  "presets": [ "latest" ]
}

as opposed to...

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

and

{
 "presets": [ "es2015" ]
}

Upvotes: -3

arakno
arakno

Reputation: 430

I ran into that same issue. Having tried every other solution on stackoverflow and beyond, adding this simple config on package.json did it for me:

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

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

Hope this helps someone.

Upvotes: 23

tomkur
tomkur

Reputation: 69

I had the same problem. When running tests I realized I actually wanted to stub dependent modules. It's good for unit testing and prevents babel from transforming submodules. So I used proxyquire, namely:

const proxyquire = require('proxyquire').noCallThru()

const myTestedModule = proxyquire('../myTestedModule', {
    'dependentModule1': { //stubbed module1 },
    'dependentModule2': { //stubbed module2 }
})

Upvotes: -1

Related Questions