How to configure setup for running ES6 tests with Mocha 6 and Babel 7?

Looking to compile a library written in ES6/7 to ES5 and store it in a dist/ folder. Additionally, I need to run tests for this library.

The development dependencies listed in my package.json file are as follows:

"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 in the package.json file are configured like this:

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

Executing npm run build successfully compiles the files into the dist/ folder.

However, when trying to run npm run test, I encounter an issue which is the main problem at hand.

> mocha --require @babel/register

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

ReferenceError: regeneratorRuntime is not defined

Initially, there was an import error that was resolved by adding a .babelrc file.

The content of my .babelrc file is shown below.

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

While researching about the regeneratorRuntime issue, I came across an article on babel-polyfill (https://babeljs.io/docs/en/babel-polyfill) stating that the polyfill may not be necessary.

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 steps are required to configure everything correctly?


Note that webpack is not being utilized in this setup.

Answer â„–1

If you are interested in testing in ES6 using Mocha and Babel 7, check out this helpful resource: https://dev.to/bnorbertjs/my-nodejs-setup-mocha--chai-babel7-es6-43ei or

To start, run the following commands:
npm install --save @babel/runtime 
npm install --save-dev @babel/plugin-transform-runtime

In your .babelrc file, make sure to add the following configuration:

{
    "presets": ["@babel/preset-env"],
    "plugins": [
        ["@babel/transform-runtime"]
    ]
}

Answer â„–2

Take a look at the official documentation:

npm install --save-dev babel-register

To set up, modify your package.json file as follows:

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

For some features, you may need to include a polyfill:

npm install --save-dev babel-polyfill
{
  "scripts": {
    "test": "mocha --require babel-polyfill --require babel-register"
  }
}

Answer â„–3

Here are the necessary steps for implementing Babel transformations and core-js polyfills in your tests file:

💡 The transformations are only applied based on the current environment, ensuring that only necessary transpilations/polyfills are done. Target environments can be specified via a .browserslist file or as a property in the package.json file. (learn more here)

Step 1: Installing required packages:

  1. @babel/core (find out why)
  2. @babel/preset-env (discover why)
  3. @babel/register (explore why)
  4. core-js (understand why)

Note that @babel/polyfill is available and utilizes core-js internally. However, it has been deprecated in favor of directly using core-js.

Step 2: Setting up a Babel configuration file named babel.config.js

(previously known as .babelrc.js or a .json file). Create this file at the root level of your codebase.

A basic configuration (for testing purposes without bundling) might look like this:

module.exports = {
  presets: [
    ['@babel/preset-env', { 
      "corejs": "3.26",   
      "useBuiltIns": "usage"
    }],
};

corejs - This library provides polyfills and should be specified with the minor version to avoid using version x.0. It becomes necessary when testing code on older Node versions that do not support all JavaScript methods. The relevance depends on your use of such methods (e.g., String.prototype.replaceAll).

useBuiltIns - must be enabled for applying the corejs polyfills. Refer to the official documentation to learn more about it.

By default, @babel/preset-env transpiles code for the current environment, but you can specify a different environment by configuring the "targets" option.


You may include additional presets like @babel/preset-react, if your code is written in React, along with any other plugins required for your code.

Step 3: Integrating mocha with the Babel configuration:

In your package.json file

In the scripts section, add a command like the following:

"test": "mocha \"src/**/*.test.js\""

Create a .mocharc.json file with the following content:

{
  "exit": true,
  "color": true,
  "require": ["@babel/register"],
  "ignore": "node_modules"
}

This setup will apply Babel transformations to all test files.

If there's a need to apply specific global JavaScript settings across all tests, another file can be added to the require setting, such as fixtures.cjs:

"require": ["@babel/register", &quo;charset=8599t;fixtures.cjs"],

fixtures.cjs:

The example below demonstrates how to incorporate a chai plugin (commonly used with Mocha) for testing DOM-related code:

var chai = require('chai'),
  chaiDOM = require('chai-dom');

exports.mochaGlobalSetup = function () {
    chai.use(chaiDOM);
}


Further reading:

  • Babel vs babel-core vs babel-runtime
  • How does mocha / babel transpile my test code on the fly?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Challenges with utilizing Node.js on zsh

Recently, I made the switch from the bash shell to zsh while running Ubuntu via WSL. Initially, Node.js was installed and up to date on bash. However, when I tried npm install on a project in zsh, I realized that Node wasn't installed for zsh. Despite ...

Execute the npm start command

Recently I began experimenting with node.js and have encountered a perplexing issue: When the server is down due to errors, I find it challenging to diagnose the problem as my npm-debug.log does not provide any useful information. Moreover, attempting to ...

What could be causing the error I'm encountering while unit testing with Jasmine/Karma?

Running the command npm install karma-jasmine –save-dev in the command line resulted in the following error: C:\Program Files\nodejs>npm install karma-jasmine -save-dev npm ERR! addLocal Could not install C:\Program Files\nodejs&b ...

Having trouble verifying a phone number using the awesome-phonenumber npm package?

I recently developed some JavaScript using the awesome-phonenumber npm package. index.js const yargs = require('yargs'); var PhoneNumber = require( 'awesome-phonenumber' ); const argv = yargs .usage('Usage: $0 -n [num]' ...

Is there a way to redirect the results of the 'find' command into a pipeline that will trigger the execution of 'more' followed by 'grep' on the package.json file located two directories above?

I'm on a quest to identify the troublesome package.json file that is triggering a dependency warning. The warning originates from a sub-module, and I have employed a find command find . -name 'foo' to reveal its location. /a/very/very/very/ ...

Revamping an npm package on GitHub

Currently, I am managing a project that has gained popularity among users and has received contributions from multiple individuals. The next step I want to take is to convert the entire library into TypeScript, but I am unsure of the best approach to ach ...

"Encountered npm error: JSON input ended unexpectedly" while trying to install express-mysql-session"

I'm currently developing a nodejs project that uses passportjs for user authentication and mysql as the database. I'm now looking to incorporate session storage by utilizing the ""express-mysql-session" package. However, when attemptin ...

The problem of "net::ERR_ABORTED" in the console is causing FontAwesome icons to fail to load

I've been attempting to import FontAwesome with SASS by using the following line: @import "../node_modules/font-awesome/scss/font-awesome"; However, I keep encountering these errors in the console and the FA icons fail to load: olympos.min.js?ver ...

Mysterious package found its way into my node_modules directory

Recently, I've been encountering a persistent package installation issue in my node_modules folder with a package named <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d8a8b0b9b6acb7b5b2abf5a8aabdbaadb1b4ac98eaf6e9f6e9ee"&g ...

Issue: 0909006C - The PEM routines are unable to retrieve the name as there is no start line

Upon cloning a project to begin working on it, I encountered an error after running yarn install and yarn start https. The error message reads: Error: 0909006C:PEM routines:get_name:no start line... The project was created by someone else and unfortunatel ...

The installation process for npm or yarn commands is dragging on for an extended period of time on my Ubuntu system

After installing Ubuntu, I encountered slow performance when running the command to install project dependencies (npm install / yarn). It took a whole 30 minutes to complete. Any ideas on what could be causing this issue? ...

I'm facing an issue where I am unable to install packages using npm due to an ERESOLVE

Every time I attempt to add an NPM package, a recurring error message appears: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @supabase/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfema ...

what is the significance of the term "On Your Network" within React?

Can you explain the meaning of "On Your Network" when running npm start in a React Project? see image Could you clarify the significance of "On Your Network: "? ...

Whenever I execute the command npm run watch, the dist folder located at the root of the project gets deleted

Exploring the folder structure of a project, particularly an open source bootstrap theme: https://i.stack.imgur.com/DjFdE.png Within the package.json file, there is a specific command: "watch": "nodemon -e scss -x \"npm run build\"", Upon run ...

Running 'npm run dev' on SiteGround server can be done by accessing the command line interface and navigating to the

I have been working on a Laravel website and now I am in the process of hosting it. A friend recommended SiteGround to me, so I purchased a plan from them for a year. I have successfully uploaded and configured my files to connect to the database correctly ...

Execute a command post-deployment on AWS Beanstalk

Encountering an issue with executing a command after deployment. I have a node.js project with a script that relies on binaries from node_modules. When I write the command for the script in .ebextensions/.config file, it executes before npm install causi ...

"There was an issue loading the gRPC binary module as it was not properly installed for this particular system" exclusive to Windows users

I encountered the following error when attempting to run my packaged app on Windows, despite it working perfectly on Linux. Expected directory: electron-v2.0-win32-ia32-unknown Found: node-v57-linux-x64-glibc This is where the expected directory should h ...

A step-by-step guide on running a git pull command before initiating npm start in Node

I'm having some trouble retrieving my files from git before starting my app. I've been using the command git pull && node ./bin/www, but the application gets stuck. Since I am new to Nodejs, I was wondering if there is a different approac ...

What are the drawbacks of relying on a dependent dependency in software development?

In a recent discussion on Stack Overflow, it was suggested that the best practice is to install packages from sub-dependencies for future use in the app, rather than directly from the dependencies node_modules folder. However, my scenario is a bit unique. ...

Best practices for placing the package.json within a tgz dependency package

I am currently working on creating a node library that will be packaged into a .tgz file. However, I am facing an issue when trying to install this library in another npm project: Error: Non-registry package missing package.json: easy-rules-core@file:/U ...