简体   繁体   English

使用 ES6 样式导入进行 mocha 测试

[英]mocha tests with ES6 style imports

I'm trying to run a Mocha test with some ES6 style imports in the file but I keep getting the error:我正在尝试使用文件中的一些 ES6 样式导入运行 Mocha 测试,但我不断收到错误消息:

import assert from 'assert';
       ^^^^^^

SyntaxError: Unexpected identifier

I tried to invoke mocha with both mocha --require @babel/register --recursive and mocha --require babel-register --recursive but the error would not go away.我试图用mocha --require @babel/register --recursivemocha --require babel-register --recursive调用 mocha 但错误不会消失。

What is the correct way to run ES6 style Mocha tests?运行 ES6 风格的 Mocha 测试的正确方法是什么?

For anyone coming from Google:对于来自 Google 的任何人:

You can also install esm: npm i esm --save-dev or use your preferred package manager.您还可以安装 esm: npm i esm --save-dev或使用您首选的包管理器。

Then pass it as an argument to mocha: mocha 'index.test.js' --require esm然后将其作为参数传递给 mocha: mocha 'index.test.js' --require esm

I found the answer to my question here -> https://dev.to/bnorbertjs/my-nodejs-setup-mocha--chai-babel7-es6-43ei我在这里找到了我的问题的答案-> https://dev.to/bnorbertjs/my-nodejs-setup-mocha--chai-babel7-es6-43ei

This package.json file这个 package.json 文件

{
  "name": "mochatest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "mocha --require @babel/register --recursive"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.1.2",
    "@babel/preset-env": "^7.5.4",
    "@babel/register": "^7.4.4",
    "mocha": "^6.1.4"
  },
  "dependencies": {}
}

together with this .babelrc连同这个 .babelrc

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

solved my problem.解决了我的问题。

Try Below Code试试下面的代码

import { strict as assert } from 'assert';

Or或者

import * as assert from 'assert';

Hope this helps希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM