Before we begin writing our tests, we'll need to add Babel to our application. Babel is a tool that is most commonly used for transforming newer versions of JavaScript into older versions of JavaScript that are compatible with browsers such as Chrome, Safari and Internet Explorer. Babel is essential because there are many newer features in JavaScript that older browsers don't understand. However, we still want to use these features because they will make our code cleaner, more efficient and easier to read. In fact, we'll be covering some of these newer JavaScript features in the next few sections. Fortunately, we don't have to worry about Chrome understanding many of these newer features - that's because Chrome is an evergreen browser that's already compatible with the features we will be using. However, if we were working on an enterprise application where it's likely some of our customers are using outdated browsers, we'd need to use tools like Babel to make our sites compatible with those browsers.

However, that's not why we need Babel for our projects. After all, we know Chrome is good to go with any new features of JavaScript we'll be using.

Our issue is that Jest uses NodeJS's require() statements instead of ES6's import and export syntax. However, we are using import and export in our applications.

Babel can solve this problem for us by transforming ES6 module syntax to the require() syntax that Jest needs. So we aren't transforming our code for other users - we are transforming our newer JavaScript syntax into syntax that our tests will be able to read.

Let's start by adding Babel to our application:

$ npm install @babel/[email protected] --save-dev

Next, we'll need to install a specific Babel plugin that will transform ES6 module syntax:

$ npm install @babel/[email protected] --save-dev

Finally, we need to set up our Babel configuration. Just as we use an .eslintrc file to configure ESLint, we'll use a .babelrc file to configure Babel. The file should go in the root directory of the project.

  "env": {
    "test": {
      "plugins": ["@babel/plugin-transform-modules-commonjs"]

The configuration above states that our test environment should use the plugin we just installed to transform ES6 modules into CommonJS modules, which is what Node uses.

This is the only Babel configuration we'll do in this course. Even though we are doing very little with it, it's good to have some exposure since this tool is very common in real world applications. If you are interested in learning more about using Babel with webpack, check out webpack's Babel documentation.

Now we're ready to start writing tests!

Lesson 25 of 46
Last updated more than 3 months ago.