运行摩卡测试时 Babel 意外令牌导入

在其他相关问题中提供的解决方案,如包括适当的预设(es2015)在。Babelrc,已经在我的项目中实现。

我有两个项目(我们称之为 A 和 B) ,它们都使用 ES6模块语法。在 ProjectA 中,我导入 ProjectB,它是通过 npm 安装的,位于 node _ module 文件夹中。当我为项目 A 运行我的测试套件时,我得到了一个错误:

SyntaxError: 意外的令牌导入

在此之前是项目 B 中所谓的错误代码行:

(函数(导出,要求,模块,_ _ 文件名,_ _ dirname){ import 来自‘ history/lib/createBrowserHistory’的 createBrowserHistory;

Iife 似乎是 npm 或者可能是 babel 相关的东西,因为我的源文件只包含“ import createBrowserHistory from‘ history/lib/createBrowserHistory’; Project B 测试套件中的单元测试运行良好,如果我从 Project A 中删除 Project B 作为依赖项,那么我的测试套件(仍然使用 es6导入内部项目模块)运行良好。

完整堆栈跟踪:

 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

以下是 package.json 中的 test 命令:

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

这篇 StackOverflow 的文章很类似,但是没有为我提供使用命令行的解决方案: 使用 babel 从 node _ module 导入模块,但失败

83284 次浏览

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:

  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.

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 }
})

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.

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/

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

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.

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'

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

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

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

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

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

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 :)

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

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

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

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.