Unit Testing Pure Functions
Build a working model of automated testing from assertions to unit, component, API, integration, contract and end-to-end tests, then apply it to a single progressive task-board capstone where each milestone adds a real defect, a failing test, a corrected implementation and an expected result.
What you will be able to do
#- Identify the unit boundary of a function.
- Test a pure function without any test double.
- Turn a discovered bug into a permanent regression test.
Overview
#The easiest tests to write are for pure functions
A pure function returns a value determined only by its arguments and produces no side effects. No clock, no network, no global state. That makes it the ideal unit: given the same input it always produces the same output, so a test needs only an input and an expected output.
function slugify(title) {
return title
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
}
console.log(slugify(' Hello World! ')); // hello-world
Define the unit
A unit is the smallest piece of behavior worth testing in isolation. For a pure function it is the function. For a method it is the method plus the class invariants it relies on. Do not test private helpers through a public function and call it a unit test of the helper; either export the helper or accept that you are testing the public behavior.
Test the contract, not the implementation
Assert on returned values and thrown errors, not on internal variables. A test that inspects a private cache passes or fails based on how the function is written, so a safe refactor breaks it. A test that checks slugify('Hello World') === 'hello-world' survives any rewrite that keeps the contract.
Turn bugs into regression tests
When you find a bug, the first step is a failing test that reproduces it. That test then guards the fix forever. This is the highest-value test you can write, because it encodes a real failure that actually happened rather than a hypothetical one.
Keep the test as simple as the code
If a test needs its own helper to compute the expected value, it may be reimplementing the function. Prefer literal expected values. expect(slugify('A B')).toBe('a-b') is clearer and safer than computing the expected slug with a second algorithm.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
What does `slugify(' Hello World! ')` return?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.javascriptfunction slugify(title) { return title.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, ''); } console.log(slugify(' Hello World! '));Exercise 2Explain
Explain why asserting on internal state makes a test brittle.
Reveal the reference answer
reference.javascriptInternal state is an implementation detail. A test that reads a private cache or a counter couples the test to how the function is written, so a refactor that preserves behavior can still break the test. Asserting on the returned value couples the test to the contract, which is what callers depend on. Behavior-preserving changes should not break tests.The answer should separate contract from implementation and explain that brittle tests punish safe refactoring.
Exercise 3Implement
Implement `capitalize(word)` that uppercases only the first character and lowercases the rest. `console.log(capitalize('hELLO'), capitalize(''), capitalize('a'))` should print `Hello A` (note the empty string yields an empty string).
starter.javascriptfunction capitalize(word) { // your code here }Reveal the reference answer
reference.javascriptfunction capitalize(word) { if (word.length === 0) return ''; return word[0].toUpperCase() + word.slice(1).toLowerCase(); }Authored expected output: Hello A
The empty-string guard prevents reading word[0] as undefined. For non-empty input, the first character is uppercased and the remainder lowercased, which handles the mixed-case input correctly.
Exercise 4Debug
A user reported that `slugify('Hello!')` returned `hello-`. Find the defect and fix it.
starter.javascriptfunction slugify(title) { return title.toLowerCase().replace(/[^a-z0-9]+/g, '-'); }Reveal the reference answer
reference.javascriptfunction slugify(title) { return title .trim() .toLowerCase() .replace(/[^a-z0-9]+/g, '-') .replace(/^-+|-+$/g, ''); }Authored expected output: hello
The original function never strips leading or trailing separators, so input with trailing punctuation or whitespace can produce a trailing dash. Adding the final replace removes boundary dashes.
Exercise 5Test
Write a regression test that reproduces the trailing-dash bug and passes only after the fix.
starter.javascriptfunction slugify(title) { return title.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, ''); }Reveal the reference answer
reference.javascriptfunction assertEqual(actual, expected, label) { if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual); } assertEqual(slugify('Hello!'), 'hello', 'punctuation stripped'); assertEqual(slugify('Hello '), 'hello', 'trailing space stripped'); console.log('slugify regression verified');Authored expected output: slugify regression verified
Both assertions reproduce the trailing-dash defect: the buggy implementation replaces the trailing punctuation and space with a dash, so both fail before the fix and pass after it. The test guards the regression permanently.
Exercise 6Interview
In an interview, describe how you decide what counts as a unit to test.
Reveal the reference answer
reference.javascriptI define the unit as the smallest behavior with a stable contract that callers depend on. For a pure helper that is the function. For a class method it is the method plus the invariants it assumes. I test through the public interface so refactors do not break tests, and I only drop to a smaller unit when a specific branch is hard to reach through the public path and the branch has enough logic to deserve its own contract.The answer should tie unit size to a stable contract and to the caller's perspective, not to file or function boundaries alone.
Common misconceptions
#- Every function needs a test double to be testable.
- A unit test must inspect internal state to be thorough.
- Testing private helpers directly is always better than testing public behavior.
Follow-up practice
#- testing-edge-cases-and-boundaries
- testing-test-doubles
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.