A Unit Test: Generate, Then Judge
Why This Matters
This is the core loop of the whole course. You let AI write a test, and then you prove whether the test is worth anything by breaking the code on purpose. A test that stays green when the code is wrong is worse than no test: it gives false confidence.
Step 1: generate
Give the AI your test list from lesson 7, Test Cases Before Code and the code:
Write Vitest unit tests for formatDuration in src/lib/runs.ts.
Use exactly these cases: <paste your table>.
Use one `it` per behaviour, with a name that describes the behaviour.
Do not change src/lib/runs.ts.
Read what you get. Check three things before running anything:
- Does every case from your list appear, with the expected value you wrote down, not a value the AI calculated from the code?
- Do the names describe behaviour (“shows minutes and zero-padded seconds”) rather than implementation (“test padStart”)?
- Is there an
expectin every test? A test without an expectation always passes.
Step 2: run
npm test
Green. But green only means the test and the code agree. It does not mean either of them is right.
Step 3: break it on purpose
Open src/lib/runs.ts and make one small, realistic mistake. Change:
return `${minutes}m ${String(seconds).padStart(2, '0')}s`
to:
return `${minutes}m ${String(seconds).padStart(1, '0')}s`
Run the tests again:
This is what a good test looks like when it catches a bug:
- It fails, so the bug cannot slip through.
- Its name tells you which behaviour broke, without reading code.
- The message shows expected versus received:
"1m 03s"versus"1m 3s". - It points to the line:
tests/lib/runs.test.ts:16.
Now put the code back:
git restore src/lib/runs.ts
npm test # green again
Make it a habit
For every test you accept, from an AI or a colleague, ask: “Which change to the code would make this test fail?” If you cannot think of one, the test probably checks nothing. Tools can automate this idea; it is called mutation testing, and TestRun Board has it (npm run mutation). You meet it again in the Agentic Engineering course.
Exercise
- Generate tests for
formatDurationwith the prompt above and review them with the three checks. - Break the code in three different ways: the
padStartchange, changing10_000to1_000, and removing thems < 0check. Which tests catch each change? Which change is not caught? - For a change that is not caught, write the missing test case in plain words, then ask the AI to add exactly that test. Restore the code with
git restore.
Key Takeaways
- Generate, review, run, break, restore: that is the loop.
- Check that expected values come from your list, not from the code.
- A good failing test names the behaviour, shows expected versus received and points to the line.
- Ask of every test: which change would make it fail?

