App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Home Guide How to write Snapshot Tests for React Components with Jest?

How to write Snapshot Tests for React Components with Jest?

By Mohit Joshi, Community Contributor -

The entire testing process is accelerated by automation testing, which increases test coverage, speed, accuracy, efficiency, and reliability. Imagine combining various automation testing techniques on your product to scale up its quality while removing the possibility of human error.

Jest snapshots are one such approach for testing JavaScript applications. Suppose you’re unfamiliar with Jest snapshot testing. In that case, here’s a step-by-step through this comprehensive tutorial to help you take snapshots as part of your front-end automated tests for validating UI by using a React application as an example. 

What is Snapshot Testing?

Snapshot testing is an automated testing procedure through which the current state of an application’s UI is captured and compared against the previously saved snapshot. It helps detect unexpected changes in the output and simplifies verifying code changes.Run testIn this kind of testing, the output of a particular code state is compared to find any unintended UI change. Let’s visualize the snapshot testing process in Jest to see the various results that can be expected during a snapshot test using Jest framework.

What are Jest Snapshots?

A snapshot in Jest results from the JavaScript or TypeScript code at a particular moment. To find any unexpected code changes, several snapshots are taken and compared. Jest generates a snapshot file when you create a test containing a serialized representation of the code output under test. 

This snapshot file acts as a “snapshot” or reference of how the code must function. The test succeeds if the two snapshots are identical; otherwise, it fails. Jest also highlights the changes between the two snapshots that contain the code difference. 

Importance of testing React components with Jest

Here are some key reasons why snapshot testing is essential for testing React components in Jest.

  • Using Snapshots to simulate UI changes for testing: While developers make every effort to implement changes exactly as a designer intended, snapshot testing helps ensure this occurs. The visual representation of a code is recorded and then compared with a screenshot of a new scenario to validate whether there is a difference.
  • Using Snapshot tests to determine whether changes were intentional: When using Jest to provide Snapshot testing for React components, you may quickly determine whether the snapshot displays the output the developer is attempting to bring. If this goes smoothly, snapshots may report it; if not, they show the output the developer did not expect.

Prerequisites

  1. You must have Node.Js installed on your system at least version 14 or higher. 
  2. Install any IDE of your choice. In this example, we are using Visual Studio Code IDE. 
  3. You must be familiar with the basic concepts of React.Js.

Setting Up and Installing Jest

Now, let’s set up our React project, and configure Jest to start 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

Writing Snapshot Tests

1. Writing React components 

Let’s create a React application for which we will write Snapshot tests using Jest. 

Write the following code inside the directory:

basic-app/src/components/HelloWorld.js.
import React from 'react'

function HelloWorld() {
return (
<div>
<h1>
Hello World
</h1>
</div>
)
}

export default HelloWorld

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

import React, { Component } from 'react';
import Items from './components/HelloWorld';

class App extends Component {
render() {
return (
<Items/>
);
}
}

export default App;

2. Using Jest’s Snapshot Feature

Once you have created the file, write the test for the following component inside the director:

src/components/HelloWorld.test.js.
import React from 'react';
import renderer from 'react-test-renderer';

import HelloWorld from './HelloWorld';

it('performs snapshot testing', () => {
const tree = renderer.create(<HelloWorld />).toJSON();
expect(tree).toMatchSnapshot();
});

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

npm test

 root directory

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

The snapshot is saved inside the directory:

components/__snapshots__/HelloWorld.test.js.snap.
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`performs snapshot testing 1`] = `
<div>
<h1>
Hello World
</h1>
</div>
`;

3. Updating Snapshots in Jest

If you change the component’s script slightly and run the test command, the terminal will display the following result highlighting the change. 

Updating Snapshots in Jest

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

jest --updateSnapshot

The jest update snapshot command comes in handy to update the snapshots quickly. 

4. Interactive Snapshot Mode in JEST

Inline snapshots are interactive due to the reason that they are saved automatically back into the source code. In simpler words, you can save screenshots automatically without switching to a .snap file. 

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

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

Integrating with BrowserStack

With  BrowserStack, you can test your web apps across multiple browsers and mobile platforms. On the other hand, the popular JavaScript testing framework Jest is used to test React apps. 

Integrating BrowserStack with Jest allows you to run your Jest tests on the devices-browsers-OS matrix available on the Real Device Cloud

Step 1: Install BrowserStack NodeSDK

To install the BrowserStack NodeSDK with the following command. 

npm i -D browserstack-node-sdk@latest
npx setup --username YOUR_USERNAME --key YOUR_ACCESS_KEY

Your username and access key are available after you log in to the BrowserStack dashboard. 

Step 2: Configure your browserstack.yml file

The browserstack.yml file is automatically generated while setting up the integration. Configure the file’s different parameters such as platform, threads per platform, and debugging features. 

Step 3: Run your test suite

To run the test suite you can prompt the following command in the terminal. 

npm run [your-test-script-name]-browserstack

With BrowserStack App Percy

  • Teams can use AI-powered visual engine processes to compare screenshots with a baseline image for any visual inconsistencies, significantly reducing noise.
  • Effortlessly integrate visual testing into your existing automation workflows.
  • Group visual changes to reduce noise and false positives for faster reviews.
  • Integrate with popular CI/CD and SCM tools such as Jenkins, Travis CI, and GitHub

How to write Snapshot Tests for React Components with Jest?

Start Testing on BrowserStack

Best Practices while Writing Snapshot Tests 

1. Consistency in naming conventions

Maintaining enough consistency while naming test files increases the project’s maintainability by clearly describing the purpose of the test files and structuring them accordingly. While documenting a naming convention, ensure your team is aware.

2. Grouping tests logically

Grouping tests logically to simplify your test files is also a good idea. This includes utilizing describe blocks to group relevant tests. This helps make the purpose of tests crystal clear. Moreover, Use ‘before’ and ‘after’ hooks to ensure the preceding test case has no impact on subsequent tests if you have complex nested code. 

If your tests are simple and easy to comprehend, it encourages collaboration in your project and increases the maintainability of the code. To do so, you can do the following things: avoid unnecessary code, use helper functions such as test.each to reduce duplication in your code, and even then, if you have complex tests, use comments to describe them. 

Conclusion

In this example, we understood how to perform the Jest snapshot tests. Although it may be used for any JavaScript code, Jest is a well-known JavaScript testing framework frequently used to test React applications. 

  • Jest enables React testing to be performed using snapshots, which is particularly helpful in identifying any unintentional UI changes on your React app. 
  • We also used a real-world example where we built a basic React app and passed the Snapshot test, which showed the output. 
  • We modified the app’s data to discover how a snapshot test sends a fail message. Later, we updated it to pass the snapshot test a second time.
Tags
Automated UI Testing Automation Testing

Featured Articles

Unit Testing of React Apps using JEST : Tutorial

Top 5 React Native UI Components in 2023

Curated for all your Testing Needs

Actionable Insights, Tips, & Tutorials delivered in your Inbox
By subscribing , you agree to our Privacy Policy.
thank you illustration

Thank you for Subscribing!

Expect a curated list of guides shortly.