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

Babel unexpected token import when running mocha tests

其他相关问题中提供的解决方案,例如including the proper presets (es2015) in .babelrc,我的项目已经实现了。

我有两个项目(我们称它们为 A 和 B),它们都使用 ES6 模块语法。在项目 A 中,我正在导入通过 npm 安装并位于 node_modules 文件夹中的项目 B。当我 运行 我的项目 A 测试套件时,出现错误:

SyntaxError: Unexpected token import

其前面是项目 B 中声称的错误代码行:

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

iife 似乎与 npm 或 babel 相关,因为我的源文件仅包含“从 'history/lib/createBrowserHistory' 导入 createBrowserHistory;项目 B 的测试套件 运行 中的单元测试很好,如果我将项目 B 作为项目 A 的依赖项删除,然后我的测试套件(仍然使用 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": "mocha --compilers js:babel-core/register '+(test|src)/**/*Spec.js'"

这个 Whosebug post 类似,但没有为我使用命令行提供解决方案:

似乎唯一的解决办法是明确包括:

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

在测试帮助文件中,并在我的测试命令中将其传递给 mocha:

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

最终解法:

添加registerBabel.js:一个单独的文件,其工作是要求babel-core/register...

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

如果您的应用程序还依赖于 babel-node,请添加 entry.js。这充当包含 es6 的应用程序的包装器。

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

然后您将 运行 您的申请 node entry

对于 mocha 测试,testHelper.js 应该需要 registerBabel.js 以及初始化 babel 支持 运行时间.

require('./registerBabel');

并且 运行 你的摩卡咖啡测试 mocha --require ./testHelper.js '+(test)/**/*Spec.js'

这将递归测试“./test”中任何以 "Spec.js" 结尾的文件。将模式替换为与您项目中的规范匹配的模式。

对于 Babel <6

解决这个问题最简单的方法是:

  1. npm install babel-preset-es2015 --save-dev
  2. .babelrc添加到项目的根目录,内容为:

    {
     "presets": [ "es2015" ]
    }
    

确保您是 运行 带有“--compilers js:babel-core/register”参数的 mocha。

对于Babel6/7+

  1. npm install @babel/preset-env --save-dev
  2. .babelrc添加到项目的根目录,内容为:

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

确保您是 运行 mocha 并带有 --compilers js:babel-register (Babel 6) 或 --compilers js:@babel/register (Babel 7) 参数

对于 mocha 版本 7 或更高版本,分别使用 --require babel-register--require @babel/register

我遇到了同样的问题。 当 运行 测试时,我意识到我实际上想要存根依赖模块。它有利于单元测试并防止 babel 转换子模块。所以我用了proxyquire,即:

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

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

我 运行 遇到了同样的问题。在 Whosebug 及其他平台上尝试了所有其他解决方案后,在 package.json 上添加这个简单的配置对我来说是可行的:

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

我所有的 ES6 导入在那之后都有效。 顺便说一句,我在 webpack.config.js 中有相同的配置,但显然这是让它也适用于 mocha 测试的唯一方法。

希望这对某人有所帮助。

你肯定会遇到这个问题,你正在使用 mocha 不知道的 ES6

所以你正在使用 babel 但你没有在测试中使用它...

几个解决方案:

一个。如果你 运行 NPM 使用

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

乙。我正在使用

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

C。来自 cli:

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

您可以在 http://www.pauleveritt.org/articles/pylyglot/es6_imports/

阅读更多内容

更适合未来的设置

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

并在 .babelrc 中

{
  "presets": [ "latest" ]
}

相对于...

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

{
 "presets": [ "es2015" ]
}

我的 .babelrc 文件中有 {"modules": false},像这样:

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

正在投掷

Unexpected token import

删除后,mocha 运行 成功。

我发现使用 babel 6.X.X 最简单的方法是使用 nyc,然后将 helper 文件添加到 pckage.json

所以这是我用的

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')();

现在您可以在测试中或任何需要的地方使用 es6。我的都失败了 ;)

然后 npm run test 将触发 nyc mocha --reporter tap 'test/**/*.spec.js'

我遇到了同样的问题,并通过阅读 babel documentation 将 Babel 与 Mocha 集成来修复它:

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

--compilers 已弃用。

我的简单解决方案:

npm install --save-dev babel-core

然后在 package.json 中添加您的测试脚本,如下所示:

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

我今天早上使用 official Using Babel instructions 中针对 Mocha 4 的以下说明解决了这个问题:

安装 NPM 模块

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

或单个命令:

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

package.json:

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

.babelrc

{
  "presets": ["env"]
}

我安装了 mocha 并且在我的代码中使用 import 时遇到了完全相同的错误。通过执行以下操作,问题已解决。

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

然后添加一个.babelrc文件:

{
    "presets": [
        "es2015"
    ]
}

然后运行mocha这样:

mocha --compilers js:babel-core/register

以下是对我有用的方法。我在使用 --compilers 标志时收到警告。

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

因此我将其替换为 --require 标志

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

这是我的 .babelrc:

{
  "presets": ["env"]
}

我的 package.json 开发依赖项

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

对于任何使用 Babel 7 和 Mocha 4 的人来说,一些包名称已经发生了一些变化,并且接受的答案有点过时了。我必须做的是:

npm install @babel/register --saveDev

并在package.json

中的测试行添加--require @babel/register

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

@babel/polyfill 修复了一些问题,例如 async/await 功能(如果您碰巧正在使用这些功能)。

希望对某人有所帮助:)

如果您使用的是 TypeScript,您可能需要 specify the extensions option

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

今天早上我按照以下说明解决了这个问题

安装 NPM 模块

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

我在此处添加另一个 ES6+mocha+babel 配置答案,当前为 19 年 6 月(参考 answer/commente 上的日期)。 mocha 已弃用 --compiler 标志,而我使用的版本即使使用 --no-deprecation 标志 c.f 也不可用。 this

请注意,我不会包含链接页面中的所有相关位,因为其中 none 让我得到了一个基于最新版本的 mocha 和 babel 的干净测试版本;这个答案应该包括让我成功测试构建的步骤。

按照此处的说明,在 this answer, and here 中,我尝试使用 npm install:

安装似乎是最低限度的最新 babel
$ npm install --save-dev mocha
$ npm install --save-dev @babel/preset-env

并且我在 package.json 中调整了 mocha 调用,如下所示:

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

这导致错误:

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

如上所述,--no-deprecation 没有帮助,请参考上面链接的页面。所以按照 here 的说明,我调整了 package.json:

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

并开始看到有关定位 babel 模块的错误,例如:

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

此时我开始安装 babel 包,直到我可以继续。我相信完整安装是这样的:

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

最后需要更改的是更新 package.json 中的 mocha 调用,删除 js: 前缀,如下所示:

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

我无法回答为什么这是必要的:如果有人可以回答这个问题,请发表评论,我会用更好的信息更新我的回答。

我做的最后一件事是在项目目录中创建一个 .babelrc,内容为:

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

我不记得是什么原因引起的,但我相信那是因为 mocha 继续抱怨无法识别我 [=58] 中的 import 关键字=].如上所述,如果有人可以回答这个问题,请发表评论,我会用更好的信息更新我的答案。