For many years I dreaded front end development. It’s not because I don’t love making products or writing CSS, but rather it was virtually impossible to properly test my UI code. UI code is particularly vulnerable to bugs: the combination of API flakiness, random user inputs, and race conditions make it incredibly easy to make logic errors. For a long time, there were not great tools for verifying the behavior of this code.

With React and the ecosystem of testing tools that have emerged around it, it’s finally possible to build robust, scalable tests that provide strong guarantees on code correctness.

The number of possibilities to test on the front end grows exponentially. User input, network, and race conditions can all introduce bugs.

When we decided to start writing UI tests for our app, we found that there weren’t any great resources that explained the various techniques for React testing. The goal of this series is to discuss these techniques and provide an overview of how to get started.

In modern JavaScript front ends, there are 3 types of tests that we might want to write:

Unit tests: these verify the behavior of individual components or modules. There are a number of tools and libraries that make writing these tests easier.

Application tests: applications and business logic are hard to fully test with unit tests. Application tests (often called “integration tests”) test your entire application code, often with a mocked-out API.

End-to-end tests: if you want to test your entire application (front end and back end), end-to-end tests allow you to make assertions that your entire system works as expected.

In this post, I’ll talk about unit tests and when / how to write them.

Unit Testing

In React, unit tests fall under a few different buckets:

Logic tests

Component tests

Storybook tests

Imagine that we’re building a “calculator” app. Each of these tests would serve a slightly different purpose: