Testing ES6 Code with Mocha and Babel

Last updated 6 months ago

How to use Mocha and Babel to test ES6+ code in a JavaScript unit test.

By default JavaScript unit tests only work with es5 code. This tutorial covers how to create custom unit tests with Babel and Mocha to test newer versions of JavaScript such as es6 and es7.

Initial Setup


To get started, create a new lesson and pick either the HTML/CSS/JS stack or the Node.js stack from the list of stacks.

Install and Setup Babel

Execute the following commands in the terminal to create a package.json file in the project and install Babel:

npm init -y
npm install babel-preset-env babel-register --save-dev

Next create a .babelrc file with the following contents:

"presets": ["env"]

Checkout Babel's docs to learn more about the options that may be specified in the .babelrc file.

Create File to be Tested

Next create a file named add.js with the following es6 code as its contents:

export const add = (a, b) => {
return a + b;

Save the files that that have been created by clicking 'Files->Save Files' in the top menubar.

Create a Custom Test

Now add a custom test and select the "Mocha with Babel (JS Unit Test)" template. Next add a Description for the test, such as ''add() function adds two numbers". For this tutorial, the default Test Contents are what we want; however, make sure to replace the default Test Contents with your test when creating custom tests. The remaining fields should not need to be changed.

As with any test, you'll need to add it to a requirement before you can run the test. For more information, checkout the article on Test & Requirement Basics.

Now click the Test button in the lab and verify that the test passes.


The final lab should look similar to the image below:

Custom Test with Mocha and Babel