How it works
The explanation, with examples you can run.
Arrange, act, assert
You don't need a framework to see the pattern. Here is a ten-line test runner and four tests for a cart total, with prices in cents to avoid floating-point surprises. The last test fails because it found a real bug. Fix cartTotal and run it again.
Press Run to see what your code prints, in order.
Runs in this browser, in an isolated frame with no access to this page. console.log, info, warn and error are shown; code runs as a classic script, so use an async function for await.
Real runners such as node:test, Vitest and Jest work the same way. They add parallel runs, watch mode, readable diffs and coverage on top.
Behaviour, not implementation
A test that checks how the code works (which private helper it called, in what order, with what internal state) breaks whenever someone restructures the code, even when nothing a caller can see has changed. People soon learn that a red test there means "update the test", and then a real failure gets the same treatment. Test through the public interface and check what comes out: a return value, a saved record, a message sent.
Keep them deterministic
Anything that changes between runs belongs outside the unit: the clock, random numbers, generated ids, environment variables, the network. Pass them in as parameters or small dependencies so the test can fix them. Then a failure always means the code changed, never that the time of day did. The next topic covers the stand-ins you pass in.
Small habits that pay off
- Write the test for a bug before fixing it, and watch it fail first. A test that has never failed might not be able to.
- Keep the arrange step short. If setup takes twenty lines, the code under test probably does too much.
- Test edge cases on purpose: empty, one, many, the boundary itself, and just past it.
- Avoid logic in tests (loops, ifs). A test should be simple enough that it obviously can't be wrong.
Check yourself
3 questions. Get them all right to finish this topic.
0 of 3 right so far. Get all three to finish this topic.