I’ve managed to write another article on React. This one is about unit testing and the things I’ve learned since I started unit testing my React components.
I go over the basics of unit testing, the most important libraries and tools you can choose from and some pitfalls I encountered on my journey.
About 2 years ago, after I joined my current company, a colleague and I had the task to start writing unit tests for our React applications and increase the code-coverage of the frontend projects. I had no prior experience in this topic, but I've learned a few things along the way, including the fact that purely focusing on code coverage isn't a good idea.
I intent this article to serve as a starter guide for developers who are new to testing React components or even unit testing in general. I won't go into the technical details here, but I'll point you to articles and books that I read and found useful.
I'll also include some practical advice on how to go about testing and some common pitfalls you might encounter at the end of the article.
I’ll leave you the links to the tools I discuss in the article. These are the essentials to unit testing in React.
In React, the most used test runner is Jest. You can run jest in watch mode, which will run your tests each time you save a file.
Enzyme has been around since December 2015. Since then, it's been a great addition to React, which simplifies testing the output of React components.
The library's first release was in March 2018. It is recommended by Facebook and aims to make testing easier.
Unlike Enzyme, react-testing-library focuses on user behaviour rather than on the implementation.
Thanks for reading and enjoy your week!