Lesson 152 of 296
Writing your own tests and edge cases
What you will learn
- Why you should test without being asked
- A tiny test helper you can write in any interview
- Table-driven tests
- An edge case checklist
- The basic syntax of a test framework (Vitest or Jest)
On this page
Why test without being asked
Testing your own code before saying "done" shows the interviewer you think like a professional engineer. It also catches your own bugs before the interviewer finds them, which scores much better.
A tiny test helper
If the environment has no test framework, write one in a few lines:
function check(name: string, actual: unknown, expected: unknown): void {
const pass = JSON.stringify(actual) === JSON.stringify(expected);
console.log(`${pass ? "PASS" : "FAIL"} ${name}`);
if (!pass) {
console.log(" expected:", JSON.stringify(expected));
console.log(" actual: ", JSON.stringify(actual));
}
}JSON.stringify compares arrays and objects by content (fine for test data; remember its limits from Lesson 66, such as key order). In Node.js you can also use the built-in node:assert module: assert.deepStrictEqual(actual, expected).
Table-driven tests
List cases as data and loop over them. Adding a case is one line:
function formatPence(pence: number): string {
const sign = pence < 0 ? "-" : "";
const abs = Math.abs(pence);
const pounds = Math.floor(abs / 100);
const rest = String(abs % 100).padStart(2, "0");
return `${sign}£${pounds.toLocaleString("en-GB")}.${rest}`;
}
function runFormatPenceTests(): boolean {
const cases: [number, string][] = [
[0, "£0.00"],
[5, "£0.05"],
[1999, "£19.99"],
[123456789, "£1,234,567.89"],
[-250, "-£2.50"]
];
let allPassed = true;
for (const [input, expected] of cases) {
const actual = formatPence(input);
if (actual !== expected) {
allPassed = false;
console.log(`FAIL formatPence(${input}): expected ${expected}, got ${actual}`);
}
}
return allPassed;
}The edge case checklist
Before saying "done", go through this list and test whichever apply:
| Category | Examples |
|---|---|
| Empty | Empty array, empty string, empty object, no rows in a file |
| One item | A single element, a single character |
| Duplicates | Repeated values, repeated keys |
| Boundaries | First and last item, 0, exactly at a limit (< vs <=) |
| Negative and zero | Negative quantities, zero prices, division by zero |
| Large input | Performance with 1,000,000 items; very long strings |
| Invalid input | Wrong types, missing fields, null, undefined, NaN, malformed text |
| Ordering | Unsorted input, already sorted, reverse sorted |
| Text quirks | Capital letters, spaces at the ends, accents, emoji |
| Time | Time zones, midnight, end of month, daylight saving changes |
| Money | Pennies, rounding, currency |
You do not need all of them every time. Choose the ones that matter for this task and say why.
Test framework basics
In real projects and many take-home tasks, you use a framework such as Vitest or Jest. They have almost the same syntax:
import { describe, it, expect } from "vitest";
import { formatPence } from "./money";
describe("formatPence", () => {
it("formats whole pounds", () => {
expect(formatPence(1000)).toBe("£10.00");
});
it("adds a leading zero to pennies", () => {
expect(formatPence(5)).toBe("£0.05");
});
it.each([
[1999, "£19.99"],
[-250, "-£2.50"]
])("formats %i as %s", (input, expected) => {
expect(formatPence(input)).toBe(expected);
});
it("throws on invalid input", () => {
expect(() => parseQuantity("abc")).toThrow();
});
});| Matcher | Checks |
|---|---|
toBe(x) | Same value with Object.is (primitives) |
toEqual(x) | Same contents (objects and arrays) |
toThrow() | The function throws |
toHaveLength(n) | Array or string length |
toContain(x) | Array includes an item |
resolves / rejects | For promises: await expect(p).resolves.toEqual(...) |
Name tests as behaviour: "rejects a booking that overlaps an existing one", not "test 3". Part 14 and Part 21 cover testing strategy in depth.
Test first when it helps
For tasks with clear rules (discounts, validation), writing a few test cases first helps you and the interviewer agree on what "correct" means. This is a light form of TDD (test-driven development, Part 21).
How to say it in an interview
"Before I say I'm done I test my own code: a normal case, then edge cases like empty input, one item, duplicates, boundaries and invalid input. I like table-driven tests because adding a case is one line. With a framework like Vitest or Jest I use describe and it blocks named after behaviour and matchers like toEqual and toThrow."
Key words
| Word | Meaning |
|---|---|
| Test case | One input with its expected output |
| Table-driven test | Many cases listed as data and checked in a loop |
| Edge case | An unusual input that can break code |
| Assertion | A check that fails if the result is wrong |
| Matcher | A test framework function like toEqual |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.