Lessons · TypeScript · arrange, act, assert, typed
Arrange, act, assert, with the fixture typed
Set up typed inputs, make the one call, check the result. The annotation on the fixture documents what the function expects and refuses a wrong one.
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 read in a hurry needs the given, the done and the expected on separate lines; a typed given is one that cannot quietly be the wrong shape.
How to think about it
Arrange with the same types the code declares. Act once. Assert what must be true, in a message that reads as a sentence.
Worked example
function check(ok: boolean, msg: string): void { if (!ok) throw new Error(msg); }function applyDiscount(prices: number[], pct: number): number[] { return prices.map(p => Math.round(p * (1 - pct / 100) * 100) / 100); }The code under test.const prices: number[] = [10, 20];Arrange, typed.
const result = applyDiscount(prices, 10);Act: the one call.
check(result.join() === '9,18', 'expected 9 and 18');Assert.
console.log('ok');okYour turn
Type the fixture.
const prices: = [5, 15]; const result = applyDiscount(prices, 0);
Solve one with the compiler running
The trap
Five acts in one test. One red line, five suspects, and the types cannot help you there.
Practise arrange, act, assert, typed on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.