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.