Unit Testing is one of the essential tools every developer should use. However, I have seen many projects making it difficult to carry out this as a practice. There are many reasons for this. For example, some might say they need to focus on feature development, and writing Unit Tests is quite an additional effort. Others might say it’s challenging to test the code that we write because it’s complicated. In either of these cases, you are missing the point.

I can recall a saying that, think of whether you have time to write Unit Tests at first place or spare time to work on the same code twice later on due to bugs and issues.

Writing Testable Code

First of all, let’s find out what are the common mistakes we do, which makes it challenging to test our code. Since I will be focusing on the frontend testing, one of the most common issues in front and code that I have seen is that it’s challenging to test the UI components. The main mistake I have seen here is that if the components become too smart, having dependencies on different code segments such as API calls, loading data, handling event operations, dealing with business logic. I have seen many developers getting frustrated writing in tests for these “heavy” components.

The easiest solution for this is to separate the components into logic and presentation. Having this separation allows us to test the view components for presentation logic, event handling, and visualization while focusing on testing other pieces of business logic separately.

Making your components testable is also a good way to make sure they are independent, reusable, and shareable. That’s absolutely crucial, especially when sharing components between projects using popular tools and platforms like Bit** (Github)**. As a matter of fact, Bit will render and test your components in isolation before pushing them to your shared collection, to make sure they are truly reusable — otherwise, there’s no point in sharing them.

Image for post

Example: exploring reusable React components shared on Bit.dev

The Vicious Cycle of Not Writing Unit Tests

From my experience, when I talk to teams, those who don’t practice Unit Tests properly (using coverage as a measurement) either start late or started in the beginning but not followed it as a practice. There could be many reasons behind this, but I will present a few examples, which will help you to see whether your case fits one of these.

#javascript #frontend #react #best-practices #unit-testing

Things to Consider when Frontend Unit Testing
1.05 GEEK