Snapshot Testing
Learn how to track changes in components through snapshot testing.
We'll cover the following
Snapshot testing to test renderings
Creating Storybook stories to show the various versions of the React components is the difficult part. While we can’t automate their acceptance, since the component’s appearance must be judged visually, we can streamline the judging process using snapshots. The idea behind a snapshot is that it captures the output and compares it to the previous version. Only those that have changed will need to be reviewed.
To create the snapshot tests, we need to install the renderer and the Jest piece of the styled-components module.
Note: It has already been installed on the Educative platform.
$ npm install --only=dev react-test-renderer jest-styled-components
In the test file, we now need to import both React and the test renderer. Within the test, the component must be rendered using the test renderer, whose result is turned into JSON and then expected to match a snapshot.
Try it yourself
-
Click “Run”, and you’ll see a test passing. This means a snapshot of your components has been taken.
-
Change something in the component, for example, change
disc
to'-'
in the code. -
Click “Run” again. You’ll now see the test failing, as the component doesn’t match the snapshot anymore.
Get hands-on with 1400+ tech skills courses.