Tips on Creating Unit Tests Using Jest

This is for newbies who want to start writing simple unit tests using Jest.

Prerequisite

What do you want to unit test?

Usually, you want to know if the function you have created is behaving properly.

How to start?

Basics

Let’s say we want to create a polygon object that has fields: sides and name.

Start with your function, focus on the basic happy case and the unhappy case.

Then, you can build up from here. Add more happy cases and unhappy cases.

The next step would be to think about possible edge cases, like for this example, negative numbers. Let your imagination do its work!


Something small but important (IMO):

Notice that we only have one expectation per “it” block. This is my preferred way for these reasons:

  1. To keep it simple.

  2. To make it easier to know where the error is.

You might be thinking, maybe it’s because the example is super simple so it's possible.

I think we can create simple and clear unit tests that are not a pain to maintain.

I’ll share some tips on how to create simple tests even when there are more bits going on in the code. See you in the next post!


There you go! Short and sweet.

Thanks for reading. What do you think of these tips? Looks weird, fun, or interesting? Do you have any strong reactions? Violent ones? (spare me, I'm scared.. but ok I’ll try my best). Have some bits to share?

Jia Oblepias

I also post on Medium 😀 Check it here https://medium.com/@jia.oblepias

https://www.linkedin.com/in/jia-oblepias/
Previous
Previous

How we brought in-app messages to our app | Part 1: Segment (CDP), a Lambda and a DynamoDB

Next
Next

Prop-drilling helps our Test Driven Development