Testing ES6 Code with Jest and Babel

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

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

Initial Setup

Stack

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 Jest

Add the following command to the project's startup script to install Jest:

npm install -g jest

Then refresh the page to run the startup script and install Jest.

Configure Jest

Next create package.json by entering the following command in the project's terminal:

npm init -y

Then add the following to package.json:

"jest": {
"testMatch": ["<rootDir>/**/**"]
}

At this point the package.json file should look similar to the following:

package.json
{
"name": "sandbox",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"jest": {
"testMatch": ["<rootDir>/**/**"]
}
}

Install and Setup Babel

Execute the following command in the terminal to install Babel:

npm install babel-preset-env --save-dev

Next create a .babelrc file with the following contents:

.babelrc
{
"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:

add.js
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 "Jest 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.

Conclusion

The final lab should look similar to the image below:

‚Äč