StoicBuilder

HandbookVIII the PalaestraUnit tests

VIIIthe Palaestra, Test it

Unit tests

1 min readUpdated 28 November

In plain words

A unit test runs one small piece of code, usually a single function, with inputs you choose and checks the exact result, without a database, network or browser.

Where you see it

Harbor's prorate function works out what a team owes when it moves from Starter to Pro halfway through a month. Next to it sits prorate.test.ts, which calls it with a dozen dates and amounts, and Vitest runs them all in under a second on every save.

lib/billing/prorate.test.tsterminal
import { describe, expect, test } from "vitest";import { prorate } from "./prorate"; describe("prorate", () => { test("charges half the difference at mid-period", () => { expect(prorate({ from: 1000, to: 3000, daysLeft: 15, daysInPeriod: 30 })).toBe(1000); });});
Amounts are in cents, so 1000 is $10.00. The expected value was worked out by hand, not by the code.

What goes wrong

  1. Testing the code against itself

    If the agent works out the expected value with the same formula the function uses, the test passes whether the formula is right or wrong. Expected values should come from a worked example on paper.

    expect(total(items)).toBe(items.reduce((sum, i) => sum + i.price, 0));
  2. Only testing the ordinary case

    Most billing bugs live at the edges: the first or last day of a period, a downgrade, a free plan, February. Add a test for each edge you can name.

  3. Testing how it works instead of what it returns

    A test that checks which helper got called breaks every time the code is reorganised, even when the answer is still right. Check the output, not the internals.

What to tell your agent

Copy this into Lovable, Bolt, Cursor or any agent
Write Vitest unit tests for prorate in lib/billing, with expected values worked out by hand rather than computed with the same formula. Cover the first and last day of the period, a downgrade, a zero-price plan and a February period, then run them and show me the output.

Quick check

Sign in to earn +10 XP for it

Your agent's test for Harbor's invoice total computes the expected value with the same reduce call the function uses. Why is that a problem?

Got a prompt that touches unit tests?

Paste it. You get a better prompt first, then the cards that explain it.

Check your own prompt

Free, no sign-up.