01 / 21

Writing
Test Cases

Learn to verify your JavaScript functions with assertions and build confidence that your code works exactly as expected.

JavaScript

What Is Testing?

Testing means running your code with known inputs and checking whether the outputs match what you expect. Instead of manually checking every result, you write small programs that verify correctness automatically.

Why Write Tests?

✓ Catch Bugs Early
Tests reveal problems the moment you introduce them, not weeks later.
✓ Refactor Safely
Change code with confidence: if all tests pass, you haven't broken anything.
✓ Document Behavior
Tests show exactly how a function is supposed to behave with real examples.

Anatomy of a Test Case

Arrange Set up your inputs and expected values { } Act Call the function with those inputs f(x) Assert Check that the result matches what you expect ✓

What Is an Assertion?

An assertion is a statement that declares something must be true. If the condition is true, nothing happens. If it is false, the assertion throws an error to tell you something is wrong.

JS
// Built-in Node.js assertion
const assert = require('assert');

// This passes silently
assert.strictEqual(2 + 3, 5);

// This throws an AssertionError!
assert.strictEqual(2 + 3, 6);

Assertions vs console.log

Assertion console.log
Purpose Automated check Manual inspection
On failure Throws error Prints value (you decide)
Scalable? Yes: run 1000s No: read each one
Reusable? Yes Not really

The Core Pattern

JS
// 1. The function you want to test
function add(a, b) {
  return a + b;
}

// 2. Write test cases using assertions
const assert = require('assert');

assert.strictEqual(add(2, 3),  5);   // ✓ pass
assert.strictEqual(add(0, 0),  0);   // ✓ pass
assert.strictEqual(add(-1, 1), 0);   // ✓ pass

console.log('All tests passed!');

Choosing Good Inputs

Don't just test the "happy path." Good tests cover edge cases and unusual inputs that might break your function.

1
Normal values: typical inputs your function will handle most often.
2
Boundary values: zeros, empty strings, single-element arrays, \( n = 1 \).
3
Negative / inverse cases: negative numbers, very large values, unexpected types.
4
Special cases: whatever is unique to your function's domain (e.g., division by zero).

How to Write a Test

1
Read the spec: understand what the function should do, its inputs, and its return value.
2
Pick an input: choose a specific value (start simple, then add edge cases).
3
Calculate the expected output: work it out by hand or from the spec.
4
Write the assertion: assert.strictEqual(fn(input), expected)
5
Run and verify: execute the file. Silence means success; an error means a bug.

Example 1: isEven

JS
function isEven(n) {
  return n % 2 === 0;
}

const assert = require('assert');

// Normal cases
assert.strictEqual(isEven(4),  true);
assert.strictEqual(isEven(7),  false);

// Edge cases
assert.strictEqual(isEven(0),  true);
assert.strictEqual(isEven(-2), true);
assert.strictEqual(isEven(-3), false);

console.log('isEven: all tests passed!');

Example 2: capitalize

JS
function capitalize(str) {
  if (str.length === 0) return '';
  return str[0].toUpperCase() + str.slice(1);
}

const assert = require('assert');

assert.strictEqual(capitalize('hello'), 'Hello');
assert.strictEqual(capitalize('a'),     'A');
assert.strictEqual(capitalize(''),      '');
assert.strictEqual(capitalize('Hello'), 'Hello');

Example 3: maxOfThree

JS
function maxOfThree(a, b, c) {
  return Math.max(a, b, c);
}

const assert = require('assert');

// Max in each position
assert.strictEqual(maxOfThree(10, 5, 3), 10);
assert.strictEqual(maxOfThree(1, 9, 4),  9);
assert.strictEqual(maxOfThree(2, 6, 8),  8);

// All equal
assert.strictEqual(maxOfThree(5, 5, 5),  5);

// Negative numbers
assert.strictEqual(maxOfThree(-3, -1, -7), -1);

Testing Arrays and Objects

strictEqual checks with ===, which fails for arrays and objects (they compare by reference, not value). Use deepStrictEqual instead.

JS
function double(arr) {
  return arr.map(x => x * 2);
}

const assert = require('assert');

// Use deepStrictEqual for arrays/objects
assert.deepStrictEqual(double([1,2,3]), [2,4,6]);
assert.deepStrictEqual(double([]),      []);
assert.deepStrictEqual(double([0]),    [0]);

How a Test Runs

Run assertion actual === expected? YES PASS No output NO FAIL AssertionError shows both values Next assertion...

Common Mistakes

✕ Swapped arguments
Writing strictEqual(expected, actual) instead of strictEqual(actual, expected). The error message becomes confusing.
✕ Using == instead of ===
strictEqual uses === on purpose. If you write your own check with ==, you might miss type mismatches.
✕ Only testing the happy path
Testing just add(2, 3) and calling it done. Missing zeros, negatives, and edge cases leaves bugs hiding.

Assertion Cheat Sheet

Method Use When Example
strictEqual Numbers, strings, booleans strictEqual(add(1,2), 3)
deepStrictEqual Arrays, objects deepStrictEqual([1],[1])
ok Truthy check ok(isEven(4))
throws Function should error throws(() => div(1,0))

Question 1 of 5

What does assert.strictEqual(actual, expected) do when actual !== expected?

Question 2 of 5

You want to test that reverseArray([1, 2, 3]) returns [3, 2, 1]. Which assertion should you use?

Question 3 of 5

Given a function isPositive(n) that returns true if \( n > 0 \), which set of test inputs is most thorough?

Question 4 of 5

What is the correct order of arguments in assert.strictEqual?

Question 5 of 5

If the function is correct, what happens when this script runs?