Documentation
Search…
Testing ES6 Code with Jest and Babel
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 content and pick either the HTML/CSS/JS stack or the Node.js stack from the list of stacks.
These stacks have jest preinstalled.

Configure Jest

Next create package.json by entering the following command in the terminal:
1
npm init -y
Copied!
Then add the following to package.json:
1
"jest": {
2
"testMatch": ["<rootDir>/**/**"]
3
}
Copied!
At this point the package.json file should look similar to the following:
package.json
1
{
2
"name": "sandbox",
3
"version": "1.0.0",
4
"description": "",
5
"main": "index.js",
6
"scripts": {
7
"test": "echo \"Error: no test specified\" && exit 1"
8
},
9
"author": "",
10
"license": "ISC",
11
"jest": {
12
"testMatch": ["<rootDir>/**/**"]
13
}
14
}
Copied!

Install and Setup Babel

Execute the following command in the terminal to install Babel:
1
npm install @babel/core @babel/preset-env --save-dev
Copied!
Next create a .babelrc file with the following contents:
.babelrc
1
{
2
"presets": ["@babel/preset-env"],
3
"targets": {
4
"node": "current"
5
}
6
}
Copied!
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
1
export const add = (a, b) => {
2
return a + b;
3
}
Copied!
Save the files that that have been created by clicking 'Files->Save Files' in the top menubar.

Create a Custom Test Check

Now add a custom test check 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 check, you'll need to add it to a task. For more information, checkout the article on Tasks.
Now click the Test button in the content preview and verify that the test passes.

Conclusion

The final content should look similar to the image below: