With the growing complexities of applications, unit testing becomes mandatory. Since we are writing code in JS, we can utilize most of the testing frameworks/libraries available for
React/web apps without requiring many changes.
We recommend using the Jest Framework plus some additional utilities like Enzyme to make a developer's life easier.
What's the use of testing UI code?
We all have asked or been asked this question at least once while working on frontend. And until recent years, the term unit testing was not very popular among FE developers. Here are some of the reasons why we should write unit tests for FE code.
It lets you capture bugs before the QA team does:
We all know that it is difficult for a QA and a dev to live in harmony. Devs do not like it when the QA team finds bugs in their work and tells them to make changes. If your code has a good test coverage, there are fewer chances of finding bugs. That's a win-win situation for both sides right?
Helps other devs understand your code better:
All the test frameworks have a
describeblock where you define what the method is supposed to do, just how you would write comments for your code.
Refactors your code:
You will start asking these questions to yourself while coding: How will I test this code?, How do I make sure that each method I write can be tested? If you already ask these questions while writing code, then you are among a small minority of developers.
Makes your code modular:
If your code is tested, there are 99% chances that it is modular, which means that you can easily implement changes in the future.
Makes debugging/implementing changes much, much easier:
There will be cases when you will be required to change a function's logic, e.g., a currency formatter function which returns a string. One way of debugging it would be to go through the UI and check if the desired output is showing up. Another smart way would be to fire your test cases, change the test results according to your desired output and let the test fail. Now change the logic inside your method to make the failed test pass.
Does NOT increase development time:
Many of us give the excuse that writing test cases will increase the development time (even I was of the same opinion). But believe me, it doesn't. During the course of development, almost half of the time is spent in debugging/bug fixing. Writing unit tests can decrease this time from 50% to less than 20%.