Tutorial

Introduction to Snapshot Testing With Jest

Published on May 25, 2017
    author

    Matthew Garcia

    Introduction to Snapshot Testing With Jest

    One of Jest’s key features is snapshot testing; a very useful tool to write quick, accurate tests.

    Creating a Snapshot

    Let’s say you have a function that makes changes:

    // changeMaker.js
    export default function changeMaker(value) {
      let pennies = value * 100;
      const quarters = Math.floor(pennies / 25);
      pennies -= quarters * 25;
      const dimes = Math.floor(pennies / 10);
      pennies -= dimes * 10;
      const nickels = Math.floor(pennies / 5);
      pennies -= nickels * 5;
      return {
        quarters,
        dimes,
        nickels,
        pennies,
      };
    }
    

    And you want to test it, because you’re a good programmer and don’t want to push untested code. You could write it as:

    import changeMaker from './changeMaker';
    
    it('gives proper change.', () => {
      expect(changeMaker(1.99)).toEqual({
        quarters: 7,
        dimes: 2,
        nickels: 0,
        pennies: 4,
      });
      expect(changeMaker(2.75)).toEqual({
        quarters: 11,
        dimes: 0,
        nickels: 0,
        pennies: 0,
      });
      expect(changeMaker(0.24)).toEqual({
        quarters: 0,
        dimes: 2,
        nickels: 0,
        pennies: 4,
      });
      // And so on
    });
    

    but that’s tedious and you keep misspelling “nickels”. Instead, you can use Jest’s toMatchSnapshot matcher:

    import changeMaker from './changeMaker';
    
    it('gives proper change.', () => {
      expect(changeMaker(1.99)).toMatchSnapshot();
      expect(changeMaker(2.75)).toMatchSnapshot();
      expect(changeMaker(0.24)).toMatchSnapshot();
      // And so on
    });
    

    The first time the test runs, it’ll create a snapshot: a serialized version of the object given to expect. On all subsequent runs, it’ll compare the value given to expect to that snapshot; if it’s equal, the expectation passes, if it doesn’t, the test fails.

    If you’re working with Git, be sure to check-in your snapshots! They’re located in the __snapshots__ folder in the same directory as your test file.

    Updating Snapshots

    Snapshot testing catches unexpected changes, but what if you wanted some of those changes? Like if you wanted to add a coin:

    export default function changeMaker(value) {
      let pennies = value * 100;
      const halfDollars = Math.floor(pennies / 50);
      pennies -= halfDollars * 50;
      const quarters = Math.floor(pennies / 25);
      pennies -= quarters * 25;
      const dimes = Math.floor(pennies / 10);
      pennies -= dimes * 10;
      const nickels = Math.floor(pennies / 5);
      pennies -= nickels * 5;
      return {
        halfDollars,
        quarters,
        dimes,
        nickels,
        pennies,
      };
    }
    

    Now your snapshot tests fail. Luckily, Jest makes it easy to update these snapshots; just pass in the -u flag:

    $ yarn run test -- -u
    

    Old, failing snapshots will be thrown out, and new ones will replace them.

    Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

    Learn more about our products

    About the authors
    Default avatar
    Matthew Garcia

    author

    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.

    Still looking for an answer?

    Ask a questionSearch for more help

    Was this helpful?
     
    Leave a comment
    

    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!

    Try DigitalOcean for free

    Click below to sign up and get $200 of credit to try our products over 60 days!

    Sign up

    Join the Tech Talk
    Success! Thank you! Please check your email for further details.

    Please complete your information!

    Become a contributor for community

    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

    DigitalOcean Documentation

    Full documentation for every DigitalOcean product.

    Resources for startups and SMBs

    The Wave has everything you need to know about building a business, from raising funding to marketing your product.

    Get our newsletter

    Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

    New accounts only. By submitting your email you agree to our Privacy Policy

    The developer cloud

    Scale up as you grow — whether you're running one virtual machine or ten thousand.

    Get started for free

    Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

    *This promotional offer applies to new accounts only.