If you're a developer, or a software engineer, or you just simply.. code, you probably have heard or been working on Unit Tests.
“A unit test is a type of software testing that focuses on validating the functionality of individual components or units of a program. These units are the smallest testable parts of an application, such as functions, methods, or classes. The primary goal of unit testing is to ensure that each unit performs as expected in isolation from the rest of the application.
In the real-world case, if you work in IT field and you are the one who writes code, you may have to also write unit tests (UTs) for what you've done. There's a lot of tools, libraries that are helping us to write UTs, however, for some specific domains such as React components testing, it's still, be tricky 😭
Not to terrify you out, instead, since I've been on some UTs for React components, try the followings:
Not just for React components, for any components, or any modules, files.. A file that contains a minimal code that functions is always easier to be tested.
Try to split your complex React components into smaller ones, give them a descriptive names. For example, try not to have a component longer than 300 lines of code.
Testing components is simply different from testing the regular modules, functions… By splitting them into separate files, you are making it much more comfortable to writing unit tests.
Try to move functions outside of the component (functions that are not involve any state, just performing logic) into a file that makes sense to your development.
For example, in your components, you may have some complex logic that handle, process the data before rendering it as a component. Instead of putting that logic inside the component, you move it into a logic file, such as, helpers/utils/common, or whatever your’re comfortable with.
It’s not just painless to write unit tests by this, but also makes the code a lot more straightforward.
We can use some popular libraries, such as Jest and React Testing Library.
This is, of course, not enough to test out every thing. You may face the situation that your component needs to be in a context, such as, Redux, global state… this is another thing that we need to learn and try to know it. However, by limitting the lines of code of a react component, and separating the logic out of it, you’re making a smoother way to your unit tests later.