Using Snapshots

Learn to use snapshots to conduct testing.

Calculating the expected value and then comparing it to dynamically calculated values is very common in Redux tests. To save typing time and make the code cleaner to read, we can use one of Jest’s greatest features, snapshots.

Instead of building the expected result, we can ask Jest to run the expect() block and save the result in a special .snap file, generating our expected object automatically and managing it for us. We do not have to write the complete code ourself. Here is the code:

//Test with snapshot
it('ADD_RECIPE', () => {
  expect(actions.addRecipe('test')).toMatchSnapshot();
});

The expected calculation is gone, and instead of using isEqual(), Jest will now compare the result of the expression inside expect() to a version it has saved on disk. The actual snapshot is placed in a __snapshots__ directory in a file with the same name as the test file plus the .snap extension:

// __snapshots__/action.test.js.snap
exports[`actions ADD_RECIPE 1`] = `
Object {
  "payload": "test",
  "type": "ADD_RECIPE",
}
`;

The structure is more complicated than that of a regular JavaScript object, but the result is exactly the same as our original expected calculation:

// Calculating the expected result
const expected = { type: 'ADD_RECIPE', payload: 'test' };

What happens when our code changes? In some cases, we want to change the structure of our action object intentionally. Jest will detect that the returned value does not match what is saved inside its snapshot file and throw an error in these cases. But if we determine that the new result is the correct one and the cached snapshot is no longer valid, we can easily tell Jest to update its snapshot version to the new one.

Get hands-on with 1200+ tech skills courses.