Writing tests that survive refactors
Tests tied to behaviour keep passing while the code underneath changes. Tests tied to structure break every time, and teach you to ignore them.
Most test suites fail in one of two ways. Either they pass while the product is broken, or they break while the product is fine. The second kind is quieter and does more damage, because it trains everyone to treat a red build as noise.
The usual cause is a test that checks how the code works instead of what it does. Rename a private function, swap a loop for a map, move a file, and twenty tests fail without a single behaviour changing.
This post is about writing the other kind: tests that only fail when a user would notice.
Test the contract, not the wiring
A function has a contract: given these inputs, it produces this output or this effect. Everything else is wiring, and wiring is what a refactor changes.
Here is a test that is welded to the wiring:
it("applies the discount", () => {
const spy = vi.spyOn(pricing, "applyPercentage");
checkout(cart, { code: "SAVE10" });
// Fails the day someone inlines applyPercentage.
expect(spy).toHaveBeenCalledWith(cart.subtotal, 10);
});And the same check written against the contract:
it("takes 10% off with SAVE10", () => {
const cart = cartWith({ price: 200_00, quantity: 1 });
const order = checkout(cart, { code: "SAVE10" });
expect(order.total).toBe(180_00);
});The second test doesn't know applyPercentage exists. You can rewrite pricing from scratch and it keeps passing, as long as the customer still pays 180.
Mocks belong at the edge
Mock the things you don't own: the network, the clock, the payment provider. Leave your own modules real. Every internal mock is a claim about structure, and structure is the thing you want to stay free to change.
Name the behaviour
A test name should read as a fact about the product. takes 10% off with SAVE10 survives a rewrite. calls applyPercentage describes an implementation that might not exist next month.
Pick the level by what breaks
No single kind of test is enough. Each catches a different class of mistake at a different price.
| Kind | Catches | Speed | Breaks on refactor |
|---|---|---|---|
| Unit | Logic errors in one function | ~5 ms | Often |
| Integration | Modules disagreeing with each other | ~200 ms | Sometimes |
| End-to-end | Broken user flows | ~8 s | Rarely |
End-to-end tests are slow, but they are the only ones that can't be satisfied by code that merely looks right. A sensible split is a handful of end-to-end tests over the flows that earn money, with faster tests filling in the edge cases underneath.
Let properties find the cases you didn't think of
Example-based tests cover the inputs you thought of. Bugs live in the ones you didn't. A property test states something that must always hold and lets a library generate inputs that try to break it.
If you can say "for every valid input, this is true", you have a property. Encode, then decode, and you get the original back. Sort twice, and the second sort changes nothing.
Good properties show up in almost every codebase:
- Round trips:
parse(format(x))equalsx. - Invariants: a balance never goes below zero.
- Idempotency: running a migration twice leaves the same state as running it once.
- Equivalence: the fast path returns what the slow, obviously correct path returns.
import fc from "fast-check";
test("slugify is idempotent", () => {
fc.assert(
fc.property(fc.string(), (input) => {
const once = slugify(input);
expect(slugify(once)).toBe(once);
}),
);
});When a property fails, the library shrinks the input to the smallest case that still fails. That report is usually the bug description.
A short checklist
Before merging a test, ask three things:
- If I rewrote the implementation and kept the behaviour, would this still pass?
- If I broke the behaviour and kept the structure, would this fail?
- When it fails, will the message tell me what a user would have seen?
Three yeses, and the test will still be earning its place a year from now.