Jest is an amazing testing tool developed by the folks at Facebook and maintained by a vast community of developers. Is one of the best ways to write and run Javascript tests. It should be really easy to setup starting from scratch, but what if we want to integrate it into an already initialized project? One which uses Babel 6 and already has a .babelrc
file.
Jest requires Babel to transpile Javascript code that doesn't normally run on NodeJS environments, most commonly ES2015 modules. Problem is Jest dropped support for Babel 6 since 24.0.0
in favour of Babel 7, which introduces a lot of changes to how devs work with Babel. Jest recommends upgrading if your project is still on Babel 6, but not all projects can upgrade quickly. This blog post is for those kinds of projects.
Let's start by installing Jest 23.6.0
since that's the last version which supports Babel 6.
# Using yarn
yarn add --dev [email protected]
# Using npm
npm install --save-dev [email protected]
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 your project requires
// like "react" for example.
],
"plugins": [
// Add any Babel plugins your project needs.
// 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 it runs and 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're using .babelrc.js
or babel.config.js
files, but the main idea remains the same.
Finally, you can run jest --init
to create your Jest config file. After that, you can customize it to your project needs. The options inside the file are well documented but if 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 save you precious time and some headaches. If you have any suggestions or comments, please leave them down below!
Happy coding!