Snapshot Testing

Create a snapshot test for the ProfileCard component to ensure UI consistency.

Snapshot tests are a very useful tool when we want to make sure that our UI does not change unexpectedly. A snapshot test case follows these steps:

  • It renders the UI component.

  • It then takes a snapshot and compares it to a reference snapshot file stored alongside the test file.

  • If both states are the same, the snapshot test is successful. Otherwise, we will get errors and need to decide whether we need to update the snapshot tests or fix our components.

Snapshot tests are great for preventing UI regression and ensuring that the application adheres to the code quality and values of our development team.

Limitation of snapshot testing

There is a minor setback with snapshot tests, however. Snapshot testing doesn’t work best with dynamic components. For example, the Post component uses timeago to display a human-readable time. This means that a snapshot of this component at time tt will be different from a snapshot of the same component at time t+1t + 1. However, there are some static components in the React application, such as LoginForm, RegistrationForm, ProfileDetails, ProfileCard, CreatePost, and more.

Writing a snapshot test

For the sake of simplicity, we will write a snapshot test for the ProfileCard components, which are straightforward and can be replicated easily.

In the src/components/profile directory, let’s create a new directory called __tests__. Then, create a new file called ProfileCard.test.js. For a snapshot test, we don’t want the data to change, so we will use a static user fixture because using userFixtures to generate a fixture will create random data every time a snapshot test is run. In the newly created file, let’s add the imports needed to create a snapshot test and define a fixture object called userData:

Get hands-on with 1200+ tech skills courses.