What are snapshot tests?
Snapshots tests are tests which tells you if the html structure of your component has changed.
They are useful for checking if changes made to code has changed how a component renders. For example, if you refactor your code and find that a snapshot test fails, this lets you know that your refactor has changed the appearance of the component.
They can:
- detect html elements which are added or removed
- detect classes and IDs added to or removed from html elements
They cannot:
- Detect changes made to styles within CSS files
Our first snapshot test
Pre-requisites:
- Node >= 8.10
- npm >= 5.6
npm install -g create-react-app
create-react-app my-app
cd my-app
npm start
The site will be available at http://localhost:3000
This is what our project folder tree currently looks like:


We have a single component in App.js, which shows the loading screen on the homepage.
There is also a file called App.test.js, which contains a test for the App
We call this type of test a 'smokescreen', because it simply checks that the component renders.
Type the following in your terminal:
npm test
We are shown this in the terminal, which is a notification that no new tests have been found:

Hit 'a' in your terminal
a
We will see the result of our test being run:

This informs us that the <App/> component was mounted without crashing.
Writing our own snapshot test
The final site will look like this:https://romantic-mahavira-837983.netlify.com/
Clone this repository: https://github.com/mmagnusen/friendlyfaces
npm install
npm install --save-dev react-test-renderer
React test renderer is a package which allows you to render React components to pure JavaScript objects.
This is an example taken from the react-test-renderer documentation:
constcalculateArea=(length=2,width=5)=>returnlength*width;
importTestRendererfrom'react-test-renderer';
functionLink(props){
return<ahref={props.page}>{props.children}</a>;
}
consttestRenderer=TestRenderer.create(
<Linkpage="https://www.facebook.com/">Facebook</Link>
);
console.log(testRenderer.toJSON());
/*
{
type:'a',
props:{href:'https://www.facebook.com/'},
children:['Facebook']
}
*/
Replace the contents of App.test.js with the following:

Renderer.create() is a method which creates an instance of testRenderer with the component which is passed to it.
toJSON() returns a JSON representation of the rendered tree.
npm test

We see a new folder called __snapshots__, and within it a new file called App.test.jsxAttribute.snap. We did not create this file, it has been automatically generated by Jest.

This snapshot file gives us a human readable view of the tree for this component. Each time the snapshot test is run, Jest will compare this snapshot file with the new file generated. If they are the same, the test will pass. If there is any difference, the test will fail.