Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running Mocha 6 ES6 tests with Babel 7, how to set up?

For a library written in ES6/7, I want to compile (to ES5) the library to a dist/ folder. I also want to run the tests (written in ES6/7) for this lib.

My dev dependencies look like this (package.json):

"devDependencies": {
  "@babel/cli": "^7.4.4",
  "@babel/core": "^7.4.5",
  "@babel/preset-env": "^7.4.5",
  "@babel/register": "^7.4.4",
  "chai": "^4.2.0",
  "mocha": "^6.1.4",
  "sinon": "^7.3.2"
},

My build and test scripts looks like this (package.json):

"scripts": {
  "test": "mocha --require @babel/register",
  "build": "babel src -d dist --presets=@babel/preset-env"
},

Running npm run build works well. The dist/ folder gets populated with transpiled files.

Running npm run test does not seem to work - this is my problem.

> mocha --require @babel/register

/Users/dro/Repos/lib/node_modules/yargs/yargs.js:1163
      else throw err
           ^

ReferenceError: regeneratorRuntime is not defined

Initially I got an import error, which was resolved by adding .babelrc file.

Below is my .babelrc file content.

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

I was reading about regeneratorRuntime and it got me to this link about babel-polyfill where they explain I shouldn't need that polyfill.

This will emulate a full ES2015+ environment (no < Stage 4 proposals) and is intended to be used in an application rather than a library/tool.

What is needed to set this up properly?


I am not using webpack.

like image 306
miphe Avatar asked Jun 20 '19 09:06

miphe


People also ask

How do you set up Babel?

Simply add a "scripts" field to your package. json and put the babel command inside there as build . This will run Babel the same way as before and the output will be present in lib directory, only now we are using a local copy. Alternatively, you can reference the babel cli inside of node_modules .


2 Answers

Look at the project documentation:

npm install --save-dev babel-register

In your package.json file make the following changes:

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

Some features will require a polyfill:

npm install --save-dev babel-polyfill
{
  "scripts": {
    "test": "mocha --require babel-polyfill --require babel-register"
  }
}
like image 111
ET-CS Avatar answered Oct 17 '22 00:10

ET-CS


Testing in ES6 with Mocha and Babel 7. Look here: https://dev.to/bnorbertjs/my-nodejs-setup-mocha--chai-babel7-es6-43ei or http://jamesknelson.com/testing-in-es6-with-mocha-and-babel-6/

npm install --save @babel/runtime 
npm install --save-dev @babel/plugin-transform-runtime

And, in .babelrc, add:

{
    "presets": ["@babel/preset-env"],
    "plugins": [
        ["@babel/transform-runtime"]
    ]
}
like image 37
Umbro Avatar answered Oct 17 '22 00:10

Umbro