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.
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 :
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
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 :
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, we need to 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
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 :
5. Inside the project directory, you will see the auto-generate __snapshots__ folder. Refer the below screenshot that we have captured during our testing.
6. Lets check out the content of our snapshot file.
This is all about unit testing using jest script and when any user re-run the jest test script, then current rendered component compare with existing snapshot files. 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 files.
In above two case, when we are performing snapshot testing, then it will throw error message in console like this below.
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.
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.
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
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, we need to 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 :
5. Inside the project directory, you will see the auto-generate __snapshots__ folder. Refer the below screenshot that we have captured during our testing.
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 and when any user re-run the jest test script, then current rendered component compare with existing snapshot files. 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 files.
In above two case, when we are performing snapshot testing, then it will throw error message in console like this below.
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.
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.
No comments:
Post a Comment