Creating Snapshots
Learn how to create a snapshot for snapshot testing.
We'll cover the following
Managing the snapshot
After writing a snapshot test, Jest will create the snapshot on the first run and store it for future reference. Snapshots should be committed to any version control systems being used, such as GitHub or GitLabs. Because they represent the expected current element tree making up a user interface, all developers need to be referencing the same tree to accurately know whether or not their current tree passes the test.
Additional tooling
An additional package is required to write snapshot tests, and different client-side frameworks require different packages to do so. A list is included below for the three most popular client-side frameworks, but we are referencing React’s react-test-renderer
package in the examples below:
- React: react-test-renderer
- Vue: jest-serializer-vue
- Angular: @angular/core/testing
If we’re using one of these (or a different package), referencing Jest’s .addSnapshotSerializer(serializer) method to include support for the package will be useful. A basic snapshot test for a button component using react-test-renderer
would look something like the one below:
import renderer from 'react-test-renderer';
import Button from '../Button';
describe('button', () => {
it('renders correctly', () => {
const tree = renderer
.create(<Button onClickHandler={jest.fn()}>Submit</Button>)
.toJSON();
expect(tree).toMatchSnapshot();
});
});
We can see above that we’re really just using a package to render a component, serializing the output of this render to JSON format, and then comparing this output to a prior snapshot using Jest’s .toMatchSnapshot()
matcher. On the first run of this test, Jest will create and store a snapshot for future reference.
The file created by the test is called an artifact. Jest leverages the pretty-format package to make the snapshots readable to developers. The artifact from above would look something like this:
exports[`renders correctly 1`] = `
<button onClick={jest.fn()}>
Submit
</button>
`;
Future testing compares states against this artifact. If the label changes and renders a label with the text Next
instead of Submit
, Jest throws an error to alert us. If the button renders a new class name, e.g., className="darkBackground"
, Jest will alert us.
Example
We can see this in action in the example below. On the first run, we see the snapshot test created. If we change something about the button, for example, adding className="darkBackground"
, and then run the test again, we see it fail:
Get hands-on with 1400+ tech skills courses.