Browse tutorial categories
On this page

Test Small Functions with Clear Inputs and Outputs

Make unit tests easier to understand by checking one behavior at a time with explicit inputs, expected results, and edge cases.

A useful unit test states what behavior matters and demonstrates it with a small example. Tests are easier to maintain when they do not depend on unrelated global state or external services.

Arrange, act, and assert

function clamp(value, minimum, maximum) {
  return Math.min(Math.max(value, minimum), maximum);
}

const actual = clamp(12, 0, 10);
const expected = 10;

if (actual !== expected) {
  throw new Error(`Expected ${expected}, received ${actual}`);
}

In a test framework, the final check would use its assertion API. Keep setup, the operation, and the expected result easy to distinguish.

Include boundaries

For clamp, test values below the minimum, inside the range, and above the maximum. Consider equal boundaries and invalid inputs if the function’s contract defines how they should behave.

Prefer behavior over implementation details

Assert observable output rather than the number of internal helper calls unless those calls are part of the behavior being tested. This lets you improve implementation without rewriting tests that merely mirror the source code.

A simple test workflow

flowchart LR
  A[Choose behavior] --> B[Arrange input]
  B --> C[Call function]
  C --> D[Assert result]
  D --> E{Pass?}
  E -->|No| F[Diagnose and fix]
  E -->|Yes| G[Keep regression test]

The test should be deterministic: the same inputs and controlled environment should produce the same result each time.

#programming#testing#code quality