Matthew Garcia
Jest is a JavaScript testing framework requiring little to no configuration. Here’s a quick post to get you up and running with it.
Are you using create-react-app? If so, Jest is already installed, so you can skip this part. Thanks, vertical integration!
It’s pretty straightforward. Install it via Yarn (or NPM):
yarn add --dev jest
And add a script for it in package.json:
"scripts": {
"test": "jest"
}
If you wanna use Babel in your tests, just install babel-jest
:
yarn add --dev babel-jest
Jest will treat any file that ends in .test.js
or .spec.js
as a test file. So, if you have a file called divide.js
, you can put a divide.test.js
next to it in the same directory and Jest will pick it up when it runs.
Jest will also consider files that are in a __TESTS__
folder to be test files, if you want to keep your tests separate.
Jest injects a number of globals into test files, so there’s nothing to import other than the stuff you want to test. So, if you have a divide.js
like:
export default function divide(dividend, divisor) {
if (divisor === 0) {
throw new Error('Division by zero.');
}
return dividend / divisor;
}
Your divide.test.js
would look something like:
import divide from './divide';
// Describe the test and wrap it in a function.
it('divides down to the nearest integer.', () => {
const result = divide(5, 2);
// Jest uses matchers, like pretty much any other JavaScript testing framework.
// They're designed to be easy to get at a glance;
// here, you're expecting `result` to be 2.5.
expect(result).toBe(2.5);
});
From there, just run your script:
yarn run test
And Jest will run your tests.
One of the best things about Jest is how easy it is to get code coverage. All you have to do is pass in the coverage
flag and Jest will handle the rest. So, for the example in the last section, just change the command to:
yarn run test -- --coverage
👑 This is just an introduction; there is so much more to Jest.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
I know this is article is just a quick intro to Jest but the use of ES6+ import/export for modules is unfortunate for an example since Jest does not yet appear to support this out of the box - and support for modules is currently, still, an experimental feature. I think the article should either use a different example or point this out.