Let’s test your async components sync!

We at Kontentino are testing our UI components with unit testing and we use with functional testing for our utility methods. But when it came to testing our UI with data asynchronously fetched from the server we just needed to find out the way how to do that simple and with maximum effectivity. We researched the web and found out that there are plenty of articles about how you could test your components with async functions. Web articles are usually recommending to fake your backend API with some tools or some dummy functions on the client-side. This approach is according to us good but it requires some amount of configuring and programming dummy code which costs additional time. 

After small brainstorming, we came up with a solution that is very effective and doesn’t cost any additional time by writing dummy code. Our approach at the end of the day can also keep your code structured. No more empty words, let’s take a look at the code.
Imagine you have a React Hook asynchronously calling API and returning some variables.

You can easily use this hook in any of your components. But if you do that your component will become dependent on the async response from API. This dependency is doing your component harder to test and the only way to do it is by writing dummy code which we talked about earlier.

Now let’s take a look at this.

Do you remember that? Yeah, Render Props they’re not dead and they are still useful. This code shows Generic component HttpGet which is a layer handling async get actions from our API. OK, but what does it mean? How can it help me with testing async functions? Don’t you know? So have a look here.

As you can see our Component HttpGet is handling async data fetching and its passing results to our View component. This means that now your logic for fetching and showing results is divided into two parts. This fact is making your component very testable because the only thing which you need to know is the possible result from API. Yes, no faked API dummy code just possible responses.

Testing time buddy. The two tests below are testing our component for two possible results from API. The first one is the loading state and the second one is returning the correct data. With this, we left API async functions behind us and we’re testing the component without any asynchronicity and only with possible API responses 🙂 We are not saying this is the best and the only one approach but it fits perfectly for us and maybe it’s gonna fit for you too. the only one approach but it fits perfectly for us and maybe it’s gonna fit for you too.

Conclusion

Instead of exactly following articles just rather take the inspiration from them and make your own solution that fits best for you and your situation.

#components#knowledge#practises#reactjs
WRITTEN BYFilip Papranec