Adding Jest to a Babel 6 project

Reading Time: 2 minutes

Jest is an amazing testing tool developed by the folks at Facebook and maintained by a vast community of developers. It is one of the best ways to write and run Javascript tests. It should be really easy to set up starting from scratch, but what if we want to integrate it into an already initialized project? A project which uses Babel 6, and already has a .babelrc file.

The problem with Babel 6

Jest requires Babel to transpile Javascript code which normally does not run on NodeJS environments, most commonly ES2015 modules. The problem is that Jest stopped supporting Babel 6 since 24.0.0 in favor of Babel 7 which introduces a lot of changes on how devs work with Babel. Jest recommends upgrading to Babel 7 if your project is still on Babel 6, but not all projects can upgrade quickly. This blogpost is for those kinds of projects.

Alternative setup

Let's start by installing Jest 23.6.0 since that's the latest version to support Babel 6.

# Using yarn
yarn add --dev jest@23.6.0

# Using npm
npm install --save-dev jest@23.6.0

Now, we need to add these lines at the bottom of our .babelrc file:

{
// Original .babelrc content...

"env": {
"test": {
"presets": [
'env'
// Add any additional presets required by your project.
// like "react" for example.
],
"plugins": [
// Add any Babel plugins required by your project.
// Most of the time you can remove this section entirely
// if you already defined your plugins somewhere up the file.
]
}
}
}

Jest sets NODE_ENV to test while running. These lines need to be present inside .babelrc so it can know your specific Babel configuration. You may need to use a slightly different syntax if you are using .babelrc.js or babel.config.js files, but the main idea remains the same.

Finally, you can run jest --init in order to create your Jest config file. After that, you can customize it according to your project needs. The options inside the file are well-documented, but in case you need additional info, check out the official configuration docs. From now on, you can start writing and running tests the standard Jest way.

Hopefully, this post will help you save some of your precious time, and avoid some headaches. If you have any suggestions or comments, please write them down below!

Happy coding!

0 Shares:
You May Also Like