Snapshots in
When a snapshot test is run, Jest compares the current output with the saved snapshot to determine if there are any differences.
To install the Jest framework, you need to enter the following command in your Windows/Linux terminal:
// For npm pakage managernpm install react-test-renderer// For yarn pakage manageryarn add react-test-renderer
Note: This shot assumes that you have already developed your React application. You can learn to creat your react application from here.
You can follow the following steps to integrate Jest with your React application:
Step 1: Navigate to your src
folder and locate App.test.js
file. You can create one if you do not have it in your folder. The naming convention of your file must be <name>.test.js
.
Step 2: After navigating your App.test.js
file, remove its contents. You do not need to do this if you're creating your own .test.js
file.
Step 3: In .test.js
file, import renderer
object from 'react-test-renderer'
library.
Step 4: Import React
object from the 'react'
module.
Step 5: Import the React application's main file (App.js
in our case).
Step 6: In the body, add the following snippet:
test("First snapshot test", ()=>{const component = renderer.create(<App/>);let tree = component.toJSON();expect(tree).toMatchSnapshot();})
Note: If you're working on the already existing
.test.js
file, then remove its components and add the above snippet after the imports.
Line 1: Creating an arrow function with the label "First snapshot test"
.
Line 2–4: Using the renderer.create
method to create an instance of the App
component and storing it in a constant component
.
Line 5: Converting the rendered component
into a JSON-like structure by calling the toJSON()
method.
Line 6: Using the toMatchSnapshot()
method from Jest to see if tree
matches the stored snapshot or not.
Now your .test.js
file will look like the one shown in the sample project below:
Open the terminal and enter the following command to run the testcases:
// For npm pakage managernpm test// For yarn pakage manageryarn test
If you do not make any changes, then your terminal will show the following message after executing the above command:
Once you enter the command, a folder named __snapshots__
will be created, which will contain the saved snapshot of your React application in App.test.js.snap
file (filename might vary).
Now, whenever you make changes to your code and run the same command above, the test cases won't pass because App.test.js.snap
file has the last snap stored in it.
The terminal will output the errors and let you know the changes you made as follows:
Jest snapshots are helpful if we want to experiment with something on our React application that might potentially lead to a crash. We can save our currently working React application somewhere and then do the experiments. This way, we can always revert to our previous state if any crashing event occurs.
Learn about Redux and how to integrate it into React applications.
Free Resources