Member-only story

Mastering Jest: Day 5 — Snapshot Testing

Introduction

Skyz Walker
2 min readJul 23, 2024
Photo by Lewis Kang'ethe Ngugi on Unsplash

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();
});
Skyz Walker
Skyz Walker

Written by Skyz Walker

I am a passionate and dedicated Web & CloudEng with a strong focus on both frontend and backend technologies. I specialize in creating stylish, modern websites.

No responses yet

Write a response