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.
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.Next create package.json by entering the following command in the 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>/**/**"]
}
}
Execute the following command in the terminal to install Babel:
npm install @babel/core @babel/preset-env --save-dev
Next create a .babelrc file with the following contents:
.babelrc
{
"presets": ["@babel/preset-env"],
"targets": {
"node": "current"
}
}
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.
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.
The final content should look similar to the image below:

Last modified 1yr ago