Unit Testing Functions

When learning to program, you often verify that your code works by printing the result to the console and manually checking if it matches your expectations.

In professional environments, checking code manually is inefficient and prone to human error. Instead, developers rely on Unit Tests.

What is a Unit Test?

A unit test is an automated program that tests a small “unit” of code independently. Usually, this unit is just a single function or two.

Rather than relying on console.log statements, a testing framework will automatically call your functions using various inputs (arguments) and strictly check if the returned value matches the expected output.

Practical Example

Imagine a function responsible for returning the monthly price of a subscription tier in pennies.

// The function to be tested
function getMonthlyPrice(tier) {
  switch (tier) {
    case "basic": return 10000;
    case "premium": return 15000;
    case "enterprise": return 50000;
    default: return 0;
  }
}

A unit test for this function would look something like this behind the scenes:

// Automated testing logic
const result = getMonthlyPrice("premium");

if (result === 15000) {
  console.log("PASS: getMonthlyPrice('premium')");
} else {
  console.error(`FAIL: Expected 15000, but got ${result}`);
}

By writing these tests, you ensure that future changes to your codebase do not accidentally break existing logic.