Hone

Lessons · TypeScript · a test function

A test is a named function that asserts one fact

A test runner such as Jest or Vitest collects every test('name', fn) call, runs each, and reports the names that failed. Each test pins one fact down.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

A fact pinned down stays true after every change anyone makes. Ten small facts about a function are worth more than one big one, because each failure names exactly what broke.

How to think about it

One fact per test. Name it as the sentence you want to read in the failure list. Call the code once, assert once, and stop.

Worked example

const assert = require('assert');
function sumPrices(prices) { return prices.reduce((a, b) => a + b, 0); }
The code under test.
function test(name, fn) { fn(); console.log(name, 'passed'); }
What a runner does, in one line.
test('total adds prices', () => assert.strictEqual(sumPrices([2, 3]), 5));
One fact.
test('empty basket totals zero', () => assert.strictEqual(sumPrices([]), 0));
A second fact, a second test. total adds prices passed / empty basket totals zero passed

Your turn

Name and write the test for a one-item basket.

test('', () => assert.strictEqual(sumPrices([9]), 9));

The trap

A test with no assert or expect. It passes whenever the code runs without throwing, which proves almost nothing.

Practise a test function on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.