10 Unit-testing React

 

This chapter covers

  • Using common testing terminology
  • Testing React components correctly
  • Adding tests for custom hooks

How do we know that our React applications work as intended? Well, we can click around and see whether everything works the way we want it to work, right? We might forget to click some button or straight up forget some unlikely but possible combination of events. Also, if we’re testing our application manually, we have to remember to do all the tests every time we change something to make sure that we didn’t break something else.

That approach, of course, is a terrible way to ensure persistent quality in your application. Instead, quality assurance is a prime candidate for automation. With automated tests, you write scripts that emulate how a user would interact with your application (at various scopes) and verify automatically that the application acts the way it is supposed to act.

We’ll jump right into testing React components by using React Testing Library (yes, that is the name of the package; it’s not all that inventive). This library has many interesting aspects and variations, so we’ll discuss a few types of components and how to test them properly. After that, we’ll test some custom hooks, setting up some hypothetical situations based on real-world examples.

10.1 Testing a static component

10.1.1 Running tests

10.1.2 Test file location

10.1.3 Test resilience

10.2 Testing interactive components

10.2.1 Testing a stateful component

10.2.2 Testing callbacks

10.2.3 Testing a form

10.2.4 Testing a hook

10.3 Testing a component with dependencies

10.3.1 Mocking the browser API

10.3.2 Mocking a library

10.3.3 Mocking a context

Summary