Test-driven development with AI in Node.js
The office rents its finest chair in started blocks of 15 minutes. Sixteen minutes costs two blocks. Your assistant has offered to “simplify” the billing logic. Before it improves the company into bankruptcy, give it an executable contract.
- Before you start
- Node.js 22 or newer, a new folder, and any coding assistant. Save the two files below in that folder.
- How you’ll know it works
- Two failing boundary cases turn green after a one-line change. The test inputs and expected results stay intact.
Write down the boundary cases
Assume whole, non-negative minutes. Zero minutes means no charge. For all other values, any part of a block counts as a full one. Write down the examples yourself before showing them to the agent. Otherwise the same misunderstanding can end up in both the code and the tests.
export function blocks(minutes) {
return Math.floor(minutes / 15);
}This initial implementation rounds down on purpose. It is plausible enough to survive a review on a Friday afternoon.
Get a meaningful red test
import test from 'node:test';
import assert from 'node:assert/strict';
import { blocks } from './meter.mjs';
for (const [minutes, expected] of [[0, 0], [1, 1], [15, 1], [16, 2]]) {
test(`${minutes} min → ${expected}`, () => {
assert.equal(blocks(minutes), expected);
});
}node --test meter.test.mjsLook at the failure messages. One minute returns 0 instead of 1; sixteen returns 1 instead of 2. Zero and fifteen already pass. A missing-module error is setup trouble. Fix the filenames before asking the assistant to diagnose the billing rule.
Give the agent a narrow repair
Run node --test meter.test.mjs and explain the two failures. Change only blocks() in meter.mjs. Keep all four cases and their expected values. Rerun the test file and report its result.Compare the returned patch with the rule. For the specified inputs, rounding up implements a started block:
export function blocks(minutes) {
return Math.ceil(minutes / 15);
}Decide whether there is anything to refactor
Run the test file again yourself. Try 30 and 31 minutes as extra checks: they should give 2 and 3. Four passing cases support the behavior you specified. They say nothing about negative numbers or fractional minutes, which you deliberately left outside the contract.
If the agent proposes a BillingStrategyFactory, it can write the proposal on the back of the chair receipt. Keep the single expression until a second rule really appears.