// Tutorial //

Introduction to Testing With Jest

Published on May 24, 2017
    Default avatar
    By Matthew Garcia
    Developer and author at DigitalOcean.
    Introduction to Testing With Jest

    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.


    Want to learn more? Join the DigitalOcean Community!

    Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

    Sign up
    About the authors
    Default avatar
    Developer and author at DigitalOcean.

    Still looking for an answer?

    Was this helpful?
    Leave a comment