How to write Snapshot Tests for React Components with Jest?

On This Page What is Snapshot Testing?What are Jest Snapshots?May 28, 2026 · 7 min read · Testing Guide

How to write Snapshot Tests for React Components with Jest?

Ensuring that React components supply consistently can be dispute as the application evolves. Even small alteration in code can lead to unexpected UI shifts. Snapshot testing with Jest provides a simple solution by capturing the rendered yield of components and allowing you to tail any unintended changes.

Overview

Snapshot testing is a method used to enchant the rendered output of a part and store it as a reference. It compares future exam resultant to the stored snapshot, foreground any unintended change in the UI.

Benefits of Snapshot Testing:

  • Quick Detection of UI Changes:Automatically flags unexpected modification in the UI after codification modifications.
  • Easy to Implement:Simple to set up with Jest and React, requiring minimal configuration.
  • Ensures Consistency:Validates that components render the like way over time, maintaining UI constancy.
  • Helps with Refactoring:Safely refactor codification, knowing that snapshot tryout will catch any unintended UI modification.
  • Supports Continuous Integration:Integrates seamlessly into CI/CD pipelines, provide automated UI proof.

This article explores Snapshot Testing for React components with Jest, continue its importance, apparatus, better recitation, and how to integrate it with BrowserStack Percy for ocular testing.

What is Snapshot Testing?

Snapshot examination is an automated testing procedure through which the current province of an application ’ s UI is entrance and compared against the antecedently saved shot. It helps detect unexpected changes in the output and simplifies verifying code change.

In this form of testing, the output of a particular codification state is compared to find any unintended UI change.

What are Jest Snapshots?

A snapshot in Jest results from the JavaScript or TypeScript codification at a especial mo. To find any unexpected code changes, several snap are taken and compared. Jest generates a snapshot file when you make a test containing a serialized representation of the code yield under test.

This snapshot file deed as a & # 8220; snapshot & # 8221; or reference of how the codification must function. The tryout win if the two snapshots are identical; otherwise, it fails. Jest too highlights the changes between the two snap that contain the code difference.

Read More:

Importance of Snapshot Testing React Components with Jest

Here are some key reason why snapshot testing is all-important for in Jest.

  • Using Snapshots to simulate UI changes for examination:While developer make every effort to implement changes incisively as a decorator destine, snapshot examination helps control this occurs. The visual representation of a code is recorded and so compared with a screenshot of a new scenario to formalise whether there is a difference.
  • Using Snapshot tests to determine whether changes be intentional:When employ Jest to provide Snapshot testing for React components, you may quick set whether the shot displays the output the developer is undertake to bring. If this go smoothly, snapshots may report it; if not, they show the output the developer did not expect.

Setting Up and Installing Jest

Before dive into writing snapshot test, it & # 8217; s important to first understand how to set up and install Jest in your labor. This insure you & # 8217; re ready to begin quiz your React components efficiently.

Prerequisites

Here are the requirement you need to have in property before writing snapshot tests for your React components.

  • You must have Node.Js installed on your scheme, at least version 14 or high.
  • Install any IDE of your choice. In this example, Optical Studio Code IDE will be used.
  • You must be familiar with the basic conception of React.Js.

Read More:

Now, Here ’ s how to set up your React project, and configure Jest to begin snapshot testing of the React components.

Step 1: Install a React application

Create a new react application with the following command. Let ’ s name this project jest-tutorial.

npx create-react-app basic-app

Next, start the app.

npm start

Step 2: Configure Jest into your project

Install react-test-renderer with the following command to render the JavaScript objects without DOM.

npm install react-test-renderer

For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.

Writing Snapshot Tests use React

Once the apparatus is complete, the next footstep is to begin writing snapshot tests for your React part. Below are the key step to efficaciously implement snapshot testing in your project.

1. Writing React element

Follow the steps to create a React covering for which Snapshot exam will be written using Jest.

Write the following code inside the directory:

basic-app/src/components/HelloWorld.js.
import React from 'react' function HelloWorld () {homecoming (& lt; div & gt; & lt; h1 & gt; Hello World & lt; /h1 & gt; & lt; /div & gt;)} export default HelloWorld

Also, update the basic-app/src/App.js file with the next script.

import React, {Component} from 'react '; import Items from './components/HelloWorld '; stratum App extends Component {render () {return (& lt; Items/ & gt;);}} export default App;

2. Using Jest & # 8217; s Snapshot Feature

Once you have create the file, write the test for the following component inside the manager:

src/components/HelloWorld.test.js.
import React from 'react '; import renderer from 'react-test-renderer '; import HelloWorld from './HelloWorld '; it ('performs snapshot examine ', () = & gt; {const tree = renderer.create (& lt; HelloWorld / & gt;) .toJSON (); expect (tree) .toMatchSnapshot ();});

After you have written the trial file, follow the command to run the test on the stem directory of your undertaking ./basic-app.

npm test

When you run a test, it will search for all the test files stored in your projection directory. To get rid of unneeded failed tests, delete the App.test.js file. Since you are not creating a test in that file, there ’ s no use in running a examination on that file.

The snapshot is save inside the directory:

components/__snapshots__/HelloWorld.test.js.snap.
// Jest Snapshot v1, https: //goo.gl/fbAQLP exports [` performs snapshot testing 1 `] = ` & lt; div & gt; & lt; h1 & gt; Hello World & lt; /h1 & gt; & lt; /div & gt; `;

3. Updating Snapshots in Jest

If you change the component & # 8217; s script slightly and run the exam bid, the terminal will exhibit the next result highlighting the modification.

If the change is intentional, you can update the shot by exhort the key ‘ u ’ in –watch mode or prompting the following command.

jest -- updateSnapshot

The jest update snap bidding comes in handy to update the snapshot cursorily.

4. Synergistic Snapshot Mode in JEST

Inline snap are synergistic due to the reason that they are salve automatically back into the source codification. In simpler words, you can save screenshots automatically without swop to a .snap file.

Let ’ s see a practical representative of how to create inline snapshots in Jest.

it ('renders correctly ', () = & gt; {const tree = renderer .create (& lt; HelloWorld/ & gt;) .toJSON (); expect (tree) .toMatchInlineSnapshot ();});

How to Perform Snapshot Testing with React in Jest Using BrowserStack Percy

BrowserStack ’ s visual fixation testing tool,, can help you enhance snapshot testing with React in Jest with robust features and seamless integrations.

Using BrowserStack Percy, running your snapshot tests with React in Jest is quite elementary. Just postdate this to set up Jest on Percy and seamlessly perform snapshot testing.

Why use BrowserStack Percy?

With BrowserStack App Percy:

  • Teams can use AI-powered visual locomotive process to compare screenshots with a baseline persona for any visual repugnance, significantly reducing noise.
  • Effortlessly integrate into your existing mechanization workflows.
  • Group visual changes to reduce noise and false positive for faster reviews.
  • Integrate with popular SCM and such as, and GitHub.

Read More:

Best Practices while Writing Snapshot Tests

To secure effective and maintainable shot test, it & # 8217; s significant to postdate sure best recitation. Here are some key guidelines to consider while writing snapshot tests for your React components.

1. Consistency in naming conventions

Maintaining adequate consistency while call test files increase the project & # 8217; s maintainability by clearly draw the purpose of the tryout files and structuring them consequently. While documenting a appellative convention, ensure your team is cognizant.

2. Grouping tryout logically

Grouping tests logically to simplify your trial file is too a good thought. This includes utilizing describe blocks to group relevant test. This aid make the design of tests crystal clear. Moreover, Use ‘ before ’ and ‘ after ’ hooks to ensure the preceding test cause has no impact on subsequent tryout if you have complex nested code.

If your tests are simple and easy to comprehend, it encourages collaborationism in your project and increases the maintainability of the codification. To do so, you can do the following things: avoid unneeded code, use helper functions such as test.each to trim gemination in your codification, and even so, if you feature complex tests, use comments to draw them.

Conclusion

Although it may be habituate for any JavaScript codification, Jest is a well-known JavaScript testing framework frequently used to examine React covering.

Jest enable React try using snapshots, which is particularly helpful in identifying unwilled UI changes in your React app.

In the instance above, a canonical React app was built, and the Snapshot test was passed, which showed the output.

The app ’ s data was change to discover how a snapshot trial sends a fail content. Later, it was update to pass the snapshot test a 2d time.

To enhance Snapshot tests on Jest, you can perform them on real device using tool like BrowserStack Percy. You can access a vast of 3500+ device-browser combinations and.

Talk to an Expert

Tags
96,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free