Member-only story
Mastering Jest: Day 5 — Snapshot Testing
Introduction
Welcome to Day 5 of our Jest journey! Yesterday, we explored the power of mocking functions and modules. Today, we’ll dive into snapshot testing, a powerful feature in Jest that helps you ensure the UI of your application remains consistent over time.
What is Snapshot Testing?
Snapshot testing is a way to track changes in your UI components. It captures the rendered output of a component and compares it to a stored snapshot. If the output changes, Jest will alert you, allowing you to review and approve or deny the changes.
Creating a Snapshot Test
Let’s see how snapshot testing works with a simple React component:
// Button.js
import React from 'react';
function Button({ label }) {
return <button>{label}</button>;
}
export default Button;
To create a snapshot test for this component:
// Button.test.js
import React from 'react';
import renderer from 'react-test-renderer';
import Button from './Button';
test('renders correctly', () => {
const tree = renderer.create(<Button label="Click Me" />).toJSON();
expect(tree).toMatchSnapshot();
});