I have came across this situation so many times where I need to write a unit test for a component pattern I have developed so many times that I can write the code with my eyes closed.
BUT what about unit testing!
That's something my mind thought is the best candidate to get rid of in order to store more cat memes.
Even when these patterns are used almost everywhere and we write the tests for each one of them (I hope you do) but still we (it can't be just me) tend to forget them and get even more confused with those pesky `act` warnings.
So I decided to curate a recipe book for some common unit tests which I come across and might be useful for future me. Happy to share the github repo and also would love to see if anyone has more such common unit testing patterns which they can add or suggest.
https://github.com/Charchit26/react-testing-library-recipes
Now, let's talk about the one I have coded a dozen times and still take half an hour to struggle with its unit tests - Loader icon while an API call is being made.
This specific example can be found here.
Here I need to render a Loading icon/text for the time being an API call is being made and once it resolves then replace the icon with something else.
Let's start with out React component under test - LoaderWithAPICall (I know such a thoughtful name!)
Now we start with out first test - it should show the loading icon initially.I am mocking the API call upfront as I know it will be called on every render and if you have got an expensive or external API call hooked up, you don't really want to keep calling it in the tests.
Here, we had to add a ``waitFor` to get rid of the `act` warnings.
If you're being troubled by the ghosts of act again and again you might need a dose of this beautiful blogpost - https://davidwcai.medium.com/react-testing-library-and-the-not-wrapped-in-act-errors-491a5629193b
Thanks David!
Now, let's go a step further and test if the API call was made and if it was then does it change the text on the screen.
Comments
Post a Comment