Jest Don’t Repeat Yourself

Marco Arras
Headstorm

--

Unit testing, everybody’s favorite part about writing code. Ok, it may not be for everyone, but maybe that’s just because you have not had the opportunity. Until recently I was in the same boat. “The code works, why do I need to test it?” Well, after writing a few myself, it didn’t actually seem so bad. I would even argue that it made me a better programmer.

It goes a little like this: “Do this, expect that. Do this, with this input, and expect this other thing.” You’re basically proving that your code will do what it was intended to do, with all the possible inputs. At the very least, it gives you confidence that your code will not break, or have any unintended consequences. Sweet, right? You can have it fail gracefully or as expected. As an added bonus, it prevents other programmers from unintentionally breaking your code in the future. You may even go back to the original function and improve it, for more usability.

Now let’s start with the code that we will be testing.

This is a simple function for the purposes of this article, that will return the band’s name, based on the name of the song. If this song, get the matching artist. (Maybe you can tell what kind of music I listen to.) Now what if we pass in a song that no one listens to? Well, with unit testing we will know what to expect. So let’s get to it.

Now we have covered all possible conditions that our function might receive. Looks good, but we can do better. I see a lot of unit test that tend to look something like this. It works, and that is great, but we are not doing a very good job about keeping it DRY. The same principles about not repeating our selves can be applied here too.

That looks so much cleaner. We are running the same test for each input, so why not just create one test? It’s easier to read, and less than half the previous lines of code. We still get the same results. I like to use the test each in the table format, but it can be a pain if you like keeping the pipes aligned. There’s plenty of documentation on it here. Just remember that it uses template literals.

Thanks for reading, let me know if you like this or would like more on it.

--

--