Snapshot testing in React Components with Jest
Tags: jest, react, webdev
Published: 2019-01-09 05:53:24

---
title: Snapshot testing in React Components with Jest
published: true
tags: jest,REACT,web development
canonical_url: 
---
--------------
Source : <a href="https://www.skptricks.com/2019/01/Snapshot-testing-React-Components-with-Jest.html" > Snapshot Testing In React Components With Jest </a>
----------------

In this tutorial we are going to learn how to perform snapshot testing in react application. Jest is a JavaScript **unit testing framework** , used by Facebook to test services and React applications.Jest acts as a **test runner, assertion library, and mocking library**. Snapshot testing is a pretty cool feature offered by Jest. It can memorize how your UI components are rendered, and compare it to the current test, raising an error if there’s a mismatch.  
  

[![Snapshot testing in React Components with Jest](https://1.bp.blogspot.com/-yMokHtmqIhc/XDIqH7huV7I/AAAAAAAACTg/sWCaiZbaoTgcVoRhUTWC9V-UoB2CdY_0QCLcBGAs/s640/snap.png "Snapshot testing in React Components with Jest")](https://1.bp.blogspot.com/-yMokHtmqIhc/XDIqH7huV7I/AAAAAAAACTg/sWCaiZbaoTgcVoRhUTWC9V-UoB2CdY_0QCLcBGAs/s1600/snap.png)
  
In order to perform snapshot testing in react application using **create-react-app** application, you need to install **react-test-renderer package** using npm command :  
  

## **Install _react-test-renderer_ package :**

```
npm install react-test-renderer
```
  
Jest also provides Snapshot testing, the ability to create a rendered ‘snapshot’ of a component and compare it to a previously saved ‘snapshot’. The test will fail if the two do not match. Snapshots will be saved for you beside the test file that created them in an auto-generate **\_\_snapshots\_\_** folder.  
  
In this demo, we are going to perform snapshot testing for  **App** component, where we have imported  **RegisterForm** component.  
  
Lets see the **RegisterFrom** and **App** component :  
  
**GitHub Project Link: **  
[https://github.com/skptricks/react/tree/master/Snapshot%20testing%20example ](https://github.com/skptricks/react/tree/master/Snapshot%20testing%20example)  
  

## **RegisterFrom .js**

```
import React from 'react';  
import './style.css';  
  
  
class RegisterForm extends React.Component {  
    constructor() {  
super();  
this.state = {  
        fields: {},  
        errors: {}  
}  
  
this.handleChange = this.handleChange.bind(this);  
this.submituserRegistrationForm = this.submituserRegistrationForm.bind(this);  
  
};  
  
    handleChange(e) {  
let fields = this.state.fields;  
      fields[e.target.name] = e.target.value;  
this.setState({  
        fields  
});  
  
}  
  
    submituserRegistrationForm(e) {  
      e.preventDefault();  
if (this.validateForm()) {  
let fields = {};  
          fields["username"] = "";  
          fields["emailid"] = "";  
          fields["mobileno"] = "";  
          fields["password"] = "";  
this.setState({fields:fields});  
          alert("Form submitted");  
}  
  
}  
  
    validateForm() {  
  
let fields = this.state.fields;  
let errors = {};  
let formIsValid = true;  
  
if (!fields["username"]) {  
        formIsValid = false;  
        errors["username"] = "\*Please enter your username.";  
}  
  
if (typeof fields["username"] !== "undefined") {  
if (!fields["username"].match(/^[a-zA-Z]\*$/)) {  
          formIsValid = false;  
          errors["username"] = "\*Please enter alphabet characters only.";  
}  
}  
  
if (!fields["emailid"]) {  
        formIsValid = false;  
        errors["emailid"] = "\*Please enter your email-ID.";  
}  
  
if (typeof fields["emailid"] !== "undefined") {  
//regular expression for email validation  
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)\*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)\*))(@((?:[\w-]+\.)\*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);  
if (!pattern.test(fields["emailid"])) {  
          formIsValid = false;  
          errors["emailid"] = "\*Please enter valid email-ID.";  
}  
}  
  
if (!fields["mobileno"]) {  
        formIsValid = false;  
        errors["mobileno"] = "\*Please enter your mobile no.";  
}  
  
if (typeof fields["mobileno"] !== "undefined") {  
if (!fields["mobileno"].match(/^[0-9]{10}$/)) {  
          formIsValid = false;  
          errors["mobileno"] = "\*Please enter valid mobile no.";  
}  
}  
  
if (!fields["password"]) {  
        formIsValid = false;  
        errors["password"] = "\*Please enter your password.";  
}  
  
if (typeof fields["password"] !== "undefined") {  
if (!fields["password"].match(/^.\*(?=.{8,})(?=.\*\d)(?=.\*[a-z])(?=.\*[A-Z])(?=.\*[@#$%&]).\*$/)) {  
          formIsValid = false;  
          errors["password"] = "\*Please enter secure and strong password.";  
}  
}  
  
this.setState({  
        errors: errors  
});  
return formIsValid;  
  
  
}  
  
  
  
  render() {  
return (  
<div id="main-registration-container">  
<div id="register">  
<h3>Registration page</h3>  
<form method="post" name="userRegistrationForm" onSubmit= {this.submituserRegistrationForm} >  
<label>Name</label>  
<input type="text" name="username" value={this.state.fields.username} onChange={this.handleChange} />  
<div className="errorMsg">{this.state.errors.username}</div>  
<label>Email ID:</label>  
<input type="text" name="emailid" value={this.state.fields.emailid} onChange={this.handleChange}/>  
<div className="errorMsg">{this.state.errors.emailid}</div>  
<label>Mobile No:</label>  
<input type="text" name="mobileno" value={this.state.fields.mobileno} onChange={this.handleChange}/>  
<div className="errorMsg">{this.state.errors.mobileno}</div>  
<label>Password</label>  
<input type="password" name="password" value={this.state.fields.password} onChange={this.handleChange} />  
<div className="errorMsg">{this.state.errors.password}</div>  
<input type="submit" className="button" value="Register"/>  
</form>  
</div>  
</div>  
  
);  
}  
  
  
}  
  
  
export default RegisterForm;
```
  

## **App.js**

```
import React, { Component } from 'react';  
import RegisterForm from './components/RegisterForm';  
//import './App.css';  
  
class App extends Component {  
  
  
  render() {  
return (  
<RegisterForm />  
);  
}  
}  
  
export default App;
```
  
Now you have to place **jest test script**  in the same directory, where you have place **App** component in your react project. Do remember **jest test script** file start with component name and followed with  **.spec.js** or . **test.js** extension. As we are performing snapshot testing for App component, so the jest test script file name should be **App.test.js**.  
  
Lets see the jest test script file :  

## **App.test.js**

```
import React from 'react';  
import App from './App';  
import renderer from 'react-test-renderer';  
  
it('renders correctly', () => {  
const tree = renderer  
.create(<App />)  
.toJSON();  
  expect(tree).toMatchSnapshot();  
});
```
  
  
Now we are done with jest test script creation and now final step is to run the test script. In order to run the jest test script in react application, then follow the below steps :  
  
1. Open the terminal or cmd prompt,  
2. Switch to your project directory in your terminal or cmd prompt.  
3. Apply below command in your command prompt.  
  
**Run Test Script**  

```
npm test
```
  
4. Wait for some time, then it will show the jest unit test script results, Refer the below unit testing test script that we have get during out testing :  

[![Snapshot testing React Components with Jest](https://4.bp.blogspot.com/-BjBGlbCeupw/XDIhRj5g-iI/AAAAAAAACSs/mVXaYqiqiVc57NO7t4g7fYxrOojYoP77wCLcBGAs/s640/11.PNG "Snapshot testing React Components with Jest")](https://4.bp.blogspot.com/-BjBGlbCeupw/XDIhRj5g-iI/AAAAAAAACSs/mVXaYqiqiVc57NO7t4g7fYxrOojYoP77wCLcBGAs/s1600/11.PNG)
  
5. Inside the project directory, you will see the auto-generate  **\_\_snapshots\_\_**  folder. Refer the below screenshot that we have captured during our testing.  
  

[![Snapshot testing React Components with Jest](https://3.bp.blogspot.com/-xV_L2RUZNv4/XDIh6Uzs6RI/AAAAAAAACS0/327EDxV5ioYdDYeB07rxIrio2dDacAVBACLcBGAs/s640/22.PNG "Snapshot testing React Components with Jest")](https://3.bp.blogspot.com/-xV_L2RUZNv4/XDIh6Uzs6RI/AAAAAAAACS0/327EDxV5ioYdDYeB07rxIrio2dDacAVBACLcBGAs/s1600/22.PNG)
  
6. Lets check out the content of our snapshot file.  

## **App.test.js.snap**

```
// Jest Snapshot v1, https://goo.gl/fbAQLP  
  
exports[`renders correctly 1`] = `  
<div  
  id="main-registration-container"  
>  
  <div  
    id="register"  
  >  
    <h3>  
      Registration page  
    </h3>  
    <form  
      method="post"  
      name="userRegistrationForm"  
      onSubmit={[Function]}  
    >  
      <label>  
        Name  
      </label>  
      <input  
        name="username"  
        onChange={[Function]}  
        type="text"  
        value={undefined}  
      />  
      <div  
        className="errorMsg"  
      />  
      <label>  
        Email ID:  
      </label>  
      <input  
        name="emailid"  
        onChange={[Function]}  
        type="text"  
        value={undefined}  
      />  
      <div  
        className="errorMsg"  
      />  
      <label>  
        Mobile No:  
      </label>  
      <input  
        name="mobileno"  
        onChange={[Function]}  
        type="text"  
        value={undefined}  
      />  
      <div  
        className="errorMsg"  
      />  
      <label>  
        Password  
      </label>  
      <input  
        name="password"  
        onChange={[Function]}  
        type="password"  
        value={undefined}  
      />  
      <div  
        className="errorMsg"  
      />  
      <input  
        className="button"  
        type="submit"  
        value="Register"  
      />  
    </form>  
  </div>  
</div>  
`;
```
  
This is all about unit testing using jest script. But lets think about the scenarios :  
1. When user changed the **App** component content or modified the **App.test.js.snap** file by mistake.  
2. User modified the App component content due to change in requirements but doesn't updated the snapshot.  
In above two case, when we are performing snapshot testing, then it will throw error message in console like this below.  
  

[![Snapshot testing React Components with Jest](https://4.bp.blogspot.com/-Gz_IleL-yWQ/XDIk7hPL2WI/AAAAAAAACTA/cc2OLXU_aeUgfvLl598hI4zFaqTgE6cUQCLcBGAs/s640/11.PNG "Snapshot testing React Components with Jest")](https://4.bp.blogspot.com/-Gz_IleL-yWQ/XDIk7hPL2WI/AAAAAAAACTA/cc2OLXU_aeUgfvLl598hI4zFaqTgE6cUQCLcBGAs/s1600/11.PNG)

[![Snapshot testing React Components with Jest](https://3.bp.blogspot.com/-haSzt4KKBB0/XDIk_uBE1ZI/AAAAAAAACTE/tpdSYwErJ_Uxt8s7REdHj8JE68ylH_A2QCLcBGAs/s640/22.PNG "Snapshot testing React Components with Jest")](https://3.bp.blogspot.com/-haSzt4KKBB0/XDIk_uBE1ZI/AAAAAAAACTE/tpdSYwErJ_Uxt8s7REdHj8JE68ylH_A2QCLcBGAs/s1600/22.PNG)
  
If you like to update the existing snapshot file with latest or new one then, you need to press u button in keyboard in your console.  
  

[![Snapshot testing React Components with Jest](https://1.bp.blogspot.com/-jW_9OXxWIfE/XDInGHuD7TI/AAAAAAAACTU/B_jIxNTfqtggdKCH0hsegcQvLOtC2kVaACLcBGAs/s640/11.PNG "Snapshot testing React Components with Jest")](https://1.bp.blogspot.com/-jW_9OXxWIfE/XDInGHuD7TI/AAAAAAAACTU/B_jIxNTfqtggdKCH0hsegcQvLOtC2kVaACLcBGAs/s1600/11.PNG)
This is all about **Snapshot testing React Components with Jest**. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.