Snapshot Tests with Jest

In the next couple of lessons, we'll cover testing, an important practice to keep source code robust. In this lesson, we'll brush upon the basics of software testing and then learn the basics of testing snapshot testing React components with Jest - Facebook's JavaScript testing library.

Software Testing

Testing source code is essential to programming, and should be seen as mandatory. We want to keep the quality of your code high and make sure everything works before using it in production. We will use the testing pyramid as our guide.

The testing pyramid includes end-to-end tests, integration tests, and unit tests. A unit test is for an isolated and small block of code, such a single function. However, sometimes units work well in isolation but not in combination with other units, so they need to be tested as a group. That’s where integration tests can help us figure out if units work well together. An end-to-end test is a simulation of a real-life scenario, such as the automated setup of a browser simulating the login flow in a web application. Where unit tests are fast and easy to write and maintain, end-to-end tests are at the opposite of the spectrum.

We want to have many unit tests covering the isolated functions. After that, we can use several integration tests to make sure the most important functions work in combination as expected. Finally, we may need a few end-to-end tests to simulate critical scenarios.

Testing React

The foundation for testing in React are component tests, generalized partly as unit tests and partly as snapshot tests. Unit tests for our components will be covered in the next chapter with a library called Enzyme. In this section, we focus on snapshot tests, using Jest.

Introduction to Jest

Jest is a JavaScript testing framework used by Facebook. It is used for component tests by the React community. Fortunately, create-react-app already comes with Jest, so you don’t need to set it up.

Jest Setup

Before you can test your first components, you have to export them from your App.js file. Afterward, you can test them in a different file.

Get hands-on with 1200+ tech skills courses.