Introduction to Testing With Jest

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.

Setting Up Jest

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

Creating Test Files

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.

Writing Tests

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.

Coverage

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

And it'll give you the coverage:

👑 This is just an introduction; there is so much more to Jest.

✖ Clear

🕵 Search Results

🔎 Searching...