What should I unit test in my code?

Finding the important and not-so-important parts to test

Hello everyone, in my previous articles, I covered the WHY, and HOW aspects of unit testing. Now is the time to explore the WHAT question.

Image for post
Image for post
Source: dev.to

Essential scenarios

We will explore it through a very basic example (JavaScript code), and see what assertions can be written. The unit test cases are written in Jest.

export function alphanumericValidator (input?: string) {  if(input is alphanumeric) {  return true;  }
else { return false; }

1. The common use case scenarios of the implementation

The unit tests should test what the code is supposed to do. The business logic implemented should be tested properly.

// test if it returns true for valid input//TEST 1: for only alphabets expect(alphanumericValidator('onlyAlphabets')).toBe(true);// TEST 2: for only numbers expect(alphanumericValidator('123')).toBe(true);// TEST 3: for both numeric and alphabets together

2. Test all the branches/conditions present in the code

All the if and else, switch cases in the code should be unit-tested.

// TEST 4: testing the else path for invalid input
// TEST 5: for special characters input

3. Test for unexpected input scenarios

We should test the error scenarios by trying to break the code and verify through test cases that the code does not break at the corner cases or unexpected input scenarios, like null/undefined values. This is especially important when we have optional parameters.

// TEST 6: for null/undefined input values

Scenarios that can be skipped

1. Static values, constants, enumerations, etc

Testing the constants, or enums, or configurations does not bring in much value. Writing test cases for these is pretty much like literally writing

2. The functionalities of external dependencies or libraries

The term unit testing means to test the unit and hence, testing the actual functionality of any dependency used in that unit does not add any value to the unit testing process. This is because the functionality of that external dependency will already have been verified and tested through separate test cases written while unit testing that unit. Hence, the point.

  1. How should I unit test my code?
    2.1. Setup
    2.2. Examples
  2. What should I unit test in my code? (this article)

Tech enthusiast, Development Specialist @teammediaocean. Creator of https://explore-a11y.netlify.app/ My motto — ‘Choose RIGHT over easy, always!’

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store