Hone

Lessons · TypeScript · arrange, act, assert

Arrange, act, assert

Set up the inputs, call the one thing being tested, check the result. Three short steps in that order, so a test can be read at a glance.

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 test is read most often when it fails, by someone in a hurry. If the given, the done and the expected are three separate lines, that person knows in seconds what the code was supposed to do.

How to think about it

Ask: what do I need before the call? What is the single call? What must be true after? If the act is two calls, it is two tests.

Worked example

const assert = require('assert');
function applyDiscount(prices, pct) { return prices.map(p => Math.round(p * (1 - pct / 100) * 100) / 100); }
The code under test.
const prices = [10, 20];
Arrange: the inputs.
const result = applyDiscount(prices, 10);
Act: the one call.
assert.deepStrictEqual(result, [9, 18]);
Assert: what must be true.
console.log('ok');
ok

Your turn

Fill in the act step.

const prices = [5];
const result = ;
assert.deepStrictEqual(result, [5]);

The trap

Asserting on several calls in one test. When it fails you get one red line and five suspects.

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