npmmocha.jsbabeljstranspiler

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.


Solution

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