Increasing the test coverage of your React project
Testing is an important and essential part of software engineering, but when working on real life projects it can get hard sometimes to cover everything properly.
Have you ever tried using snapshot testing in your React project, but always ended up finding it very dull and useless? Me too.
My main concern with snapshot testing was, how hard it is to identify the actual issue when a test is breaking, and always ending up updating meaningless classNames that have changed for some reason, when I modified some different parts of the code.
But then one day I realised that it doesn't have to be this way and snapshot testing can be in fact very useful with Jest.
Lets say we have a small component which holds very little logic. It is
rendering different statuses based on a prop called currStatus
.
As you see if the currStatus
equals loading
a simple paragraph is being
rendered with the text “loading” in it, and the same logic goes for success
and error
.
You would normally test this component by adding a data-testid
to each
paragraph tag and then test each possibility and expect it to be present.
This would be a good solution, but it requires some extra code and in case it breaks, you would have to console log things to see how has your html actually changed.
However, if you write the same with snapshot testing it becomes way more clear:
As you can see, jest takes care of matching the snapshot for you and you spare
at least 1 line of code for each test. (that is a lot of lines when you have
lots of tests)
In case something changed and the test breaks you can easily identify what has
happened:
It seems like the prop has changed and now an unknown status is being passed
down so the default scenario is being rendered (null).
This might not seem as a very big improvement, but when you are trying to write
tests for all your components it can save you a lot of time.
So next time an inexperienced startup founder or CTO needs some convincing why
you are using snapshot tests, now you know how to prove them wrong!😊
Testing is an important and essential part of software engineering, but when working on real life projects it can get hard sometimes to cover everything properly.
Adding code to existing codebases can sometimes take a lot of time. What if I told you there are ways to reduce it?