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.