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 projec
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 }
})
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.
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.
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.
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.
You might need to specify the extensions option if you're using TypeScript:
require("@babel/register")({
extensions: ['.jsx', '.js', '.ts', '.tsx']
})
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/