Skip to content

Testing That Pays for Itself

Summary

Shows which tests to write first, from smoke tests to end-to-end tests of the money and sign-in paths, and how tests become instructions an agent cannot forget.

Concepts Covered

This chapter covers the following 27 concepts from the learning graph:

Concept Concept Impact Score
Software Testing 105
Bug 41
Reproducing a Bug 13
Root Cause 12
Manual Testing 1
Automated Test 103
Test Runner 1
Unit Test 26
Integration Test 25
End-to-End Test 3
Browser Test Tool 1
Smoke Test 10
Test Fixture 1
Mocking a Service 1
Critical User Path 22
Test the Money Path 10
Test the Auth Path 10
Regression Test 5
Invariant Test 4
Rule Enforced in Code 3
Test as Agent Instruction 2
Asking the Agent for Tests 1
Test-Driven Development 2
Failing Test First 1
Test Coverage 2
Coverage Is Not Safety 1
Flaky Test 1

Prerequisites

This chapter builds on concepts from:


Moving Day

Two friends move into a rented apartment on a hot Saturday in August. The truck is half unloaded, they're arguing over who gets the bigger bedroom, and boxes are stacked along every wall. Nobody flips every light switch or opens every kitchen drawer to see if it sticks. But before the first night, one of them locks the front door and tries the handle from outside. The other opens the cabinet under the kitchen sink, finds the water shut-off valve and turns it to make sure it isn't stuck. Then somebody turns the stove knob off and holds a hand over the burner to be sure.

They don't test the apartment at random, and they don't test all of it. They test the few things that would hurt them if they were wrong, and they test them in a way that gives a clear yes or no. A drawer that sticks gets found in a week and costs nothing. A front door that doesn't lock gets found when something is missing.

Test the Locks First

Sawyer waving welcome The checks that pay off are the ones on things you can't see break. By the end of this chapter you'll know which few tests to ask your agent for first, and how to read one well enough to trust it. Gate or wall? The walls get tests.

Software testing works the same way. The natural first move after building something is to click around the screens you just made, which are the drawers. The lock and the shut-off valve go untested, because nothing about them looks broken. This chapter is about testing the locks first. It is also about a second job tests do once an AI agent writes your code. They hold rules in place that the agent would otherwise forget.

Bugs, and Where They Start

A bug is a place where software does something other than what its builder meant it to do. The word covers a crash, a wrong number, a page that shows another member's data, and a message that never goes out. Some bugs are loud. The page goes blank and someone writes in within the hour. The dangerous bugs are quiet. They return a result that looks fine, so nobody reports them.

When a bug is reported, the first job is to make it happen again on purpose. Reproducing a bug means finding the exact steps, data and conditions that make the bug appear, so that anyone can trigger it and watch it happen. Until you can reproduce a bug, you can't tell whether a fix worked. You can only hope. A builder who asks an agent to "fix the problem with scheduled messages" without a way to reproduce it will get a change and a confident summary. Neither tells you the problem is gone.

The second job is to find where the bug starts. The root cause is the first wrong thing in the chain of events that ends in the bug. It is the one line, setting or assumption that, once corrected, stops the bug and others like it. The symptom is what someone sees. The root cause is what made it happen. Agents are good at treating symptoms. Asked to stop a wrong number showing on screen, an agent may add code that hides the number, which leaves the cause in place to show up somewhere else.

Symptom or Cause?

Sawyer thinking A symptom fix and a root-cause fix both make the bug vanish from the screen. The difference shows up a month later, when the same cause breaks something else. So ask what the fix changed, not only what it made go away.

A Worked Bug: The Scheduler That Marked Too Much

The dating-safety app sends text-message reminders on a schedule. A background job sends each pending reminder and marks its row in the database as sent. Some members said reminders never arrived, yet their rows said "sent." Nothing crashed, and the job ran on time. (The bug is from the dating-safety app; the reminders and complaints around it are illustrative.)

To reproduce it, put three pending reminders in a test database, with IDs 1, 2 and 3, and mark only reminder 2 as sent. Reminders 1 and 2 both come back marked, every time. That rules out the text-message vendor, which was working fine, and points at the code that marks rows. The root cause was one comparison. The code marked every row whose ID was less than or equal to the one just sent (<=), where it should have marked only the row with that ID (=). The fix was one character.

Chapter 11 walks through this bug row by row, because at heart it's a database mistake. This chapter cares about the step after the fix: turning the reproduction into a test, so the bug can't quietly come back.

Tell your agent

"Before you change any code for this bug, write down the exact steps that make it happen, using test data. Run those steps and show me the bug happening. Then tell me the root cause in one sentence, and explain why fixing it there stops the bug, rather than hiding it."

Checking by Hand and Checking by Code

Software testing is the work of checking that software does what it should, by running it with known inputs and comparing what it does against what you expected. A test has three parts. It sets up a situation, does something, and checks the result. "Sign in as a member, open someone else's scan, expect to get nothing back" is a test, whether a person does it or a program does.

There are two ways to run that test. Manual testing is a person checking the software by using it: clicking through screens, typing into forms and looking at what comes back. Every builder does it, and it is good at some things. A person notices that a page looks wrong, that a button is confusing, or that the score feels off. No program does that well.

Manual testing has two weaknesses. It is slow, so it gets skipped when a deadline is close. And it only tests what the person thinks to try. A builder clicking through the results page after a change won't think to sign in as a second member and try to open the first member's scan. Nothing about the change seemed to touch access.

An automated test is a small program that runs part of your app with known inputs and checks the result, then reports pass or fail with no person involved. It runs in seconds, it runs the same way every time, and it runs the checks nobody remembers to try. Once written, it costs almost nothing to run a thousand times.

The tests in a project are run by a test runner, a program that finds every test, runs them, and reports which passed and which failed. In a JavaScript app like the dating-safety app, common test runners are Vitest and Jest. You or your agent start the runner with a command such as npm test, and it prints a list of results ending in a count of passes and failures. Chapter 17 shows how to make the runner run on its own every time code is pushed, so a failing test blocks the change instead of waiting for someone to notice.

Here is what an automated test looks like. This one is the scheduler bug's reproduction, written as a test. The test line names what the test checks. The lines before expect set up three reminders and mark one as sent. Each expect line states what must be true, and the runner fails the test if it isn't.

test("marking one reminder sent leaves the others pending", async () => {
  await addReminders([{ id: 1 }, { id: 2 }, { id: 3 }]);

  await markSent(2);

  expect(await status(1)).toBe("pending");
  expect(await status(2)).toBe("sent");
  expect(await status(3)).toBe("pending");
});

You don't need to write tests like this yourself. You do need to read one well enough to see what it checks, because that is how you know whether the agent tested the thing you asked about. In this one, the first expect line is the important one. It would have failed on the old code, because reminder 1 got marked sent by mistake.

Reading Code You Didn't Write

Sawyer encouraging If the test still looks like a foreign language, that's normal on a first read. Read only the expect lines first. Each one is a plain statement of what must be true, and the setup above them can wait.

Manual and automated testing each have a place. The table below sorts some checks from the dating-safety app by which kind suits them.

Check Better done by hand Better done by code Why
The results page reads clearly on a phone Yes Judging clarity needs a person
A signed-out visitor can't open any scan Yes Must hold after every change, and nobody thinks to retry it
A member can't open another member's scan Yes The failure is invisible unless you try it on purpose
The welcome email sounds friendly Yes A matter of taste
A paid member gets their scan credits once, and only once Yes Money mistakes are quiet and costly
No report ever contains a home address Yes A product rule that must hold for every input
The new score gauge looks better than the old circle Yes A judgment about looks

The pattern follows Chapter 1. Good-enough-for-now parts are mostly checked by hand, when someone gets to it. Must-be-right parts are checked by code, every time.

Tell your agent

"Show me how to run this project's tests, and run them now. Tell me how many tests there are, how many pass, and which parts of the app they cover, in plain words. If there is no test runner set up, tell me what you'd install and change to add Vitest, and wait for my go-ahead."

Kinds of Automated Tests

Automated tests come in sizes, depending on how much of the app one test runs at once. Small tests are fast and point straight at the broken line. Large tests are slow but check that the pieces work together. A healthy app has some of each.

A unit test checks one small piece of code on its own, usually one function, with no database, network or browser involved. The function that turns eight check results into a trust score is a good subject. Give it eight results, and check the score. A unit test runs in a few milliseconds, so a project can have hundreds and still finish in seconds. When one fails, it names the function that broke.

An integration test checks that several pieces work together, such as a route, the code behind it and the database. "Send a request to the scan route as member A, asking for member B's scan, and check that the server answers 404 (not found)" is an integration test. It starts the server code, talks to a test database, and checks what comes back. Integration tests are slower than unit tests. They catch a different kind of bug, where the function is right but was wired up wrong, or the route forgot to call it.

An end-to-end test checks a whole user journey through the running app, the way a member would do it: open the site, sign in, upload a photo, wait for the score, read the result. It runs everything, from the browser to the server to the database. End-to-end tests catch problems no smaller test can, such as a button that calls the wrong route. They are also the slowest and most fragile tests, so an app needs only a few, aimed at its most important journeys.

End-to-end tests for a web app usually run through a browser test tool. This is a program that opens a web browser and drives it the way a person would, clicking buttons and typing into fields. Then it checks what appears on the page. Playwright and Cypress are the common ones. The dating-safety app's builder already had browser tests running alongside unit tests, which put the app ahead of many built the same way.

A smoke test is a short, quick check that the app is alive and its main paths respond, run right after a deploy or a big change. The name comes from electronics: switch the new board on and see whether smoke comes out. For the dating-safety app, a smoke test might load the home page, sign in as a test member and start a scan, and finish in under a minute. It doesn't prove much is correct. It proves nothing is badly broken, which is the first thing you want to know after shipping. Chapter 14 places the smoke test in a deploy checklist, and Chapter 12 covers uptime checks that run a similar test every few minutes.

Here are the four side by side.

Kind What one test covers Speed When it fails, you learn How many to have
Unit test One function Milliseconds Which function is wrong Many
Integration test A route with its code and database Under a second Which connection is wrong A good number, on important routes
End-to-end test A whole journey in a browser Seconds to a minute That a journey is broken somewhere A few, on critical journeys
Smoke test The main paths, lightly Under a minute in total That the app is alive or not One short set, run after each deploy

You can practice telling them apart in the diagram below.

Diagram: Which Kind of Test Is This?

Run the Which Kind of Test Is This? MicroSim Fullscreen

Which Kind of Test Is This?

Type: microsim sim-id: test-kind-sorter
Library: p5.js
Status: Specified
Bloom Level: Analyze
Bloom Verb: classify
Learning Objective: The learner will classify ten test descriptions from the dating-safety app as unit, integration, end-to-end or smoke tests, with at least eight of ten correct.

Prerequisites: automated test, unit test, integration test, end-to-end test, browser test tool, smoke test (all defined in the section "Kinds of Automated Tests").

Evidence of Mastery: The learner assigns each of ten test cards to one of four bins and presses Check. An assignment is correct when it matches the Correct kind column in Content. Mastery is 8 of 10 correct on the first attempt. Opening a card's hint is exploration, not evidence.

Misconceptions: (1) Any test that touches the database is an end-to-end test. (2) A smoke test is just a small end-to-end test of one feature. (3) A test that checks something important must be an end-to-end test.

Instructional Rationale: Classifying requires the learner to look at how much of the app each test runs, rather than at what topic it covers. Several cards share a topic (sign-in, the score) but differ in size, so the learner has to sort by scope.

Content:

# Card text Correct kind Why (feedback)
1 Give the scoring function eight "not checked" results and check that it returns 50 Unit One function, no database or browser.
2 Send a request to the scan route as member A for member B's scan, and check the server answers 404 Integration A route, its code and the database working together.
3 Open a browser, sign in, upload a photo, wait for the score and check the results page shows it End-to-end A whole journey through the running app in a browser.
4 After a deploy, load the home page, sign in as a test member and start one scan Smoke A quick check that the main paths are alive, run after shipping.
5 Give the phone-number formatter "6125550100" and check it returns "(612) 555-0100" Unit One small function on its own.
6 Send a signed test payment event to the webhook route and check the member's credits in the test database went up by one Integration A route, signature check and database together, with no browser.
7 In a browser, sign in as a viewer and check that the Delete button is missing and that deleting by direct request fails End-to-end Drives the full app through a browser as a user would.
8 Give the report builder a people-search result with an address in it and check the report has no address Unit One function with fixed input.
9 Call the health route and the sign-in page on production and check both answer within two seconds Smoke Light and quick; it proves the app responds, not that it is correct.
10 Save a scan through the scan service and read it back from the test database Integration Code and database together.

Provenance: Cards 1, 2, 6, 7 and 8 come from the dating-safety app in research/seed-notes.md (neutral 50, 404 for a wrong ID, payment webhook, viewer role, no-locate) and this chapter. Cards 4 and 9 follow the smoke-test description in this chapter. Cards 3, 5 and 10 are illustrative and must be labeled "illustrative."

Rules: Unit = one function, no database, network or browser. Integration = two or more pieces including a route or the database, no browser. End-to-end = drives the app through a browser as a user. Smoke = a short check run after a deploy that the main paths respond. Each card has exactly one correct kind.

Learner Activity:

  1. The learner sees ten cards in a shuffled stack and four empty bins labeled Unit, Integration, End-to-end and Smoke.
  2. The learner drags each card into a bin. A hint on each card asks "Does it use a browser? A database? Is it run after a deploy?" Cards can be moved until Check.
  3. The learner presses Check. Each card shows correct or incorrect and its Why text.
  4. The learner should notice that cards 2 and 7 both test access but are different kinds, because one uses a browser.

Feedback: Ten cards, shuffled, one attempt. Correct: "Right. " plus the Why text. Incorrect: "This one is [correct kind]. " plus the Why text. If cards 2 and 7 land in the same bin, add: "Same topic, different size. Ask how much of the app the test runs." Show "n of 10 correct" and "Mastery reached" at 8 or more.

Starting State: Four empty bins and a stack of ten cards. The prompt reads "How much of the app does each test run?"

Chapter Anchors: Unit tests run in milliseconds. A smoke test for the dating-safety app finishes in under a minute. Common browser test tools are Playwright and Cypress. Common test runners are Vitest and Jest.

Tell your agent

"List every test in this project and label each one unit, integration or end-to-end. Then tell me which of our routes have no integration test at all. Don't write new tests yet."

Fixtures and Stand-Ins

Every test starts from a known situation. A test fixture is the fixed data or setup a test starts from, so it runs the same way every time. It might be a test member with a known email, three reminders with IDs 1, 2 and 3, a sample photo, or a saved copy of what a vendor returned last Tuesday. Fixtures are usually stored as files in the project, next to the tests. When a test fails, the fixture tells you exactly what went in.

Saved vendor responses are the most useful fixtures in an app like the dating-safety app. Chapter 9 explains why vendor responses need checking before the app trusts them. Keep a folder of recorded responses, with personal details replaced by made-up ones. A test can then feed the adapter a normal answer, an empty answer, an error and a reply in an unexpected shape, all without calling the vendor.

That leads to the second tool. Mocking a service means replacing an outside service with a stand-in during a test, so the test gets a canned answer instead of calling the vendor itself. The dating-safety app has eight checks backed by paid vendors. A test that called them for real would cost money on every run, would fail whenever a vendor had a slow minute, and could never test what happens when a vendor is down. A mock fixes all three. It answers instantly, it answers the same way every time, and you can tell it to fail.

Mocks have one trap. A mock returns what you told it the vendor returns. If the vendor changes its format, the mock keeps returning the old one and every test still passes. Two habits keep mocks accurate. Build them from recorded vendor responses rather than from memory, and refresh those fixtures now and then. And never mock the code you are testing. Agents sometimes mock so much that the test checks only that the mock returned what the mock was told to return.

Tell your agent

"For each outside service this app calls, save one successful response, one empty response and one error response as fixture files, with any personal data replaced by made-up values. Then show me which of our tests use these fixtures and which call the real service."

What to Test First

A builder who reads the sections above and decides to test everything will run out of time before reaching what matters. The question that makes testing pay is which tests to write first. The answer comes straight from Chapter 1. Test the must-be-right parts before anything else, and among those, test the paths a user takes through them.

A critical user path is a journey through the app where a failure would hurt a user, lose money or expose private data. Most apps have only a few. In the dating-safety app there are three that matter most: paying, signing in and reaching only your own scans, and getting a truthful score. Chapter 1's tip already asked for a test that turns off every vendor and expects a score of 50. This section takes on the other two, because in the dating-safety app those are the ones that went untested.

Test the Money Path

The money path is every step between a member deciding to pay and the app giving them what they paid for. In the dating-safety app it works like this. The member clicks Buy and pays on Stripe's checkout page. Stripe charges the card, then sends a webhook to the app's server: a message saying "this payment succeeded." Chapter 2 explains webhooks. The server checks that the message really came from Stripe by verifying its signature. Then it adds scan credits to the member's account.

In the dating-safety app, the route that received the payment webhook had no tests. Nothing showed it was broken, and that is the problem. A webhook bug doesn't appear on any screen the builder looks at. A member pays and gets no credits, or a forged message hands out free credits, or Stripe sends the same event twice and the member is credited twice. Stripe resends an event when your server doesn't answer with a success code in time, and its documentation warns that an endpoint can receive the same event more than once, so the last one is a matter of when, not if.

To test the money path is to write automated tests for every step where money changes hands or paid access is granted, starting with the webhook. Here are the four tests that cover the dating-safety app's webhook. Each uses a fixture: a saved copy of a Stripe "payment succeeded" event.

Test Sends Expects
Good payment The fixture event with a valid signature The member's credits go up by exactly the amount bought
Same event twice The same signed event two times Credits go up once, not twice
Forged event The fixture event with a wrong signature The server rejects it and credits don't change
Unknown member A signed event for a member who doesn't exist The server records the problem and changes nothing

These are integration tests. They send a request to the webhook route and check the test database. None of them calls Stripe, so they're free to run and take under a second each. Stripe's own libraries include a helper for signing a test event with a test secret, so the agent doesn't need to fake anything clever.

Test the Auth Path

The auth path is every step that decides who someone is and what they may reach. Chapter 7 teaches the checks themselves: authentication on every route, an ownership check on every object, roles enforced on the server. This section is about proving those checks are there, and keeping them there.

In the dating-safety app, the route modules had no tests. The routes did a lot right. A wrong scan ID returned 404, so a member couldn't even learn whether someone else's scan existed. But no test held that in place, and one gap did get through: a viewer role that was never enforced on the server. The screens hid the edit buttons from viewers, and the server accepted their edits anyway. A browser test that only looked at the screen would have passed. A test that skipped the browser and sent the request straight to the server would have failed, and found the gap.

To test the auth path is to write automated tests that try each kind of access that should be refused, and check that the server refuses it. These tests go on every route that returns or changes private data. For each such route, the dating-safety app needs at least these:

  • A signed-out request gets 401 (not signed in) and no data.
  • Member A asking for member B's scan gets 404 and no data.
  • A viewer sending a change gets refused, by a request sent straight to the server, not through the screen.
  • Member A asking for their own scan gets it. A test that only checks refusals would pass on a route that refuses everyone.

The last item is easy to skip. Without it, a route broken so badly that nobody can use it would pass every auth test.

The diagram below lays out both paths, step by step, with the tests that guard each step.

Diagram: The Money Path and the Auth Path

Run the Money Path and the Auth Path MicroSim Fullscreen

The Money Path and the Auth Path

Type: workflow sim-id: critical-paths-map
Library: Mermaid
Status: Specified
Bloom Level: Understand
Bloom Verb: explain
Learning Objective: The learner will explain, for each step of the money path and the auth path in the dating-safety app, what goes wrong for a member if that step breaks and which test would catch it.

Prerequisites: critical user path, webhook, signature, integration test, 401 and 404 status codes, viewer role (defined in this chapter and in Chapters 2 and 7).

Evidence of Mastery: Before opening each step's infobox, the learner chooses from three options what happens to a member if the step breaks. A choice is correct when it matches the Harm column in Content. Mastery is 7 of 9 steps correct on the first attempt. Opening an infobox after answering is exploration.

Misconceptions: (1) If the checkout page works, the money path works. (2) Hiding a button on screen protects the action behind it. (3) An auth test only needs to check that bad requests are refused.

Instructional Rationale: Explaining requires the learner to connect each step to its consequence. Predicting the harm before the infobox reveals it makes the learner reason about each step, rather than read a list.

Content:

Two left-to-right flows, each node clickable. Each node's infobox shows Harm if broken, the three answer options (Harm plus the two distractors), and Test that catches it.

Path Step Harm if broken (correct option) Distractor 1 Distractor 2 Test that catches it
Money 1. Member clicks Buy and pays on Stripe's page Member can't pay; noticed quickly by the builder Member is charged twice Member sees another member's scan Smoke test that opens checkout
Money 2. Stripe sends the "payment succeeded" webhook Member pays and gets nothing Member's photos leak Nothing; Stripe fixes it Integration test: good payment raises credits
Money 3. Server verifies the signature Anyone can forge a payment and get free credits Member can't sign in The score is wrong Integration test: forged event is rejected
Money 4. Server adds credits once per event A retried event credits the member twice Member can't pay Nothing, retries never happen Integration test: same event twice credits once
Money 5. Member starts a paid scan Paid member is blocked from scanning Member sees another member's data Stripe refunds the payment End-to-end test: buy then scan
Auth 1. Request arrives at a scan route Nothing on its own; the next steps decide The whole app goes down Member is charged none (entry point)
Auth 2. Server checks the member is signed in A stranger reads private scans Member is charged twice The page looks wrong Integration test: signed-out gets 401
Auth 3. Server checks the scan belongs to the member One member reads another's private photos The score is wrong Member can't pay Integration test: member A gets 404 for B's scan
Auth 4. Server checks the member's role allows the action A viewer changes or deletes data A viewer can't sign in Nothing, the button is hidden Integration test: viewer's change sent straight to server is refused
Auth 5. Server returns the scan to its owner The owner can't see their own scan A stranger sees it Member is charged Integration test: member A gets their own scan

Auth step 1 has no question; it is the starting node and its infobox reads "Every request enters here. The checks after it decide what happens." The nine steps with questions are Money 1 to 5 and Auth 2 to 5.

Provenance: The webhook route and route modules being untested, the viewer role not enforced on the server, and 404 for a wrong ID come from research/seed-notes.md. Stripe's webhook flow and retries follow this chapter's section "Test the Money Path." Distractors are illustrative.

Rules: Each node uses a Mermaid click directive that opens its infobox. Nodes whose step has no test in the dating-safety app at the start of the story (Money 2, 3, 4 and Auth 2, 3, 4) carry a marker "untested in the dating-safety app"; the marker's meaning is shown in a legend. Answer options are shown in a fixed shuffled order per node.

Learner Activity:

  1. The learner sees both paths with all nodes closed.
  2. The learner clicks a node. Before the infobox opens, three harm options appear; the learner picks one.
  3. The infobox opens, shows whether the pick was right, the correct harm and the test that catches it.
  4. The learner repeats for each node. The learner should notice that the untested steps are the ones whose failures can't be seen on screen.

Feedback: Nine questions, any order, one attempt each. Correct: "Right." plus the test that catches it. Incorrect: "Not quite. If this step breaks: [Harm]." plus the test. Show "n of 9 correct" when all nine are answered.

Starting State: Both paths shown, untested markers visible, all infoboxes closed. The prompt reads "Click a step. What happens to a member if it breaks?"

Chapter Anchors: The money path has four webhook tests: good payment, same event twice, forged event, unknown member. The auth path needs at least four tests per route: signed-out gets 401, another member's scan gets 404, a viewer's change is refused, the owner gets their own scan. A wrong ID returns 404.

Tell your agent

"Write integration tests for our payment webhook route, using a saved Stripe event as a fixture and Stripe's test signing helper. Cover four cases: a good payment adds credits once, the same event sent twice adds credits once, a wrong signature is rejected with no change, and an unknown member changes nothing. Run them and show me which pass and which fail. Don't change the route yet."

Tell your agent

"For every route that returns or changes a member's data, write four integration tests that send requests straight to the server: signed out gets 401, another member's ID gets 404, a viewer's change is refused, and the owner gets their own data. Put the results in a table, one row per route, and flag every failing test."

Tests That Hold a Line

Some tests check that a feature works. Others exist to stop something from happening again, or from ever happening at all.

Regression Tests

A regression test is a test written after a bug is fixed, which reproduces the bug and fails if it ever comes back. The word "regression" means sliding back. Code slides back more often than people expect. A later change restores an old version of a function. An agent rewrites the scheduler from scratch and makes the same two-character mistake. Someone copies the old code into a new job.

The scheduler test from earlier in this chapter is a regression test. Its first expect line fails if a send ever marks an earlier row again, whoever or whatever rewrites the code. The habit that turns a bug into a regression test is short: reproduce the bug as a test, watch the test fail, fix the code, and watch the test pass. The test stays in the project for good. Over a year, these tests become a record of every quiet failure the app has had, each one guarded.

Name It After the Bug

Sawyer giving a tip Ask the agent to name each regression test after the bug it guards, in words a member would understand. When it fails a year from now, the name alone tells you what came back.

Invariant Tests

Some rules aren't about one bug. They are about something that must hold for every input, forever. An invariant test checks that a product rule holds across many inputs, not just one example: for every fixture, for every route, for every kind of report, the rule is never broken.

The dating-safety app's no-locate rule is the clearest case. The app must never return a person's home address, workplace or location, even when a vendor sends one. In the dating-safety app, no test enforced it yet. The rule was in the data model and the output code, and it was written down. But nothing failed if a change broke it.

Here is how an invariant test for no-locate works. It loads every saved people-search fixture, including ones that hold addresses, workplaces and map coordinates. It runs each one through the code that builds a member's report. Then it searches the finished report for each address, workplace and coordinate from the fixture, and for any field named like address, street, employer, lat or lng. The test fails if it finds a single one.

A one-example test An invariant test
Takes one fixture with one address Takes every fixture, including ones built to tempt the code
Checks that this address isn't in the report Checks that no address, workplace or coordinate from any fixture is in any report
Passes if the code handles this case Passes only if the rule holds everywhere it was tried
Misses a new vendor field such as work_location Catches it, as long as a fixture holds a workplace

When a new vendor is added, the agent adds that vendor's fixtures to the folder, and the invariant test checks them with no other change. The rule now guards itself.

Rule Enforced in Code

The no-locate test shows a larger idea. A rule enforced in code is a product or safety rule written as a test or automated check that fails when the rule is broken. The rule then holds even when nobody remembers it. A rule in a document or an instruction file depends on someone reading it at the right moment. A rule in a test depends on nothing but the test runner.

A Sign or a Lock

Sawyer thinking Think of the instruction file as a sign on the door and the test as the lock. The sign works when someone reads it. The lock works every time someone tries the handle.

Chapter 1 listed a heuristic: test each product rule the day you write it. Here is what that looks like for the dating-safety app's three product rules.

Product rule Written down as Enforced in code by
No false all-clear "A check that didn't run is never counted as passed" A test with every vendor mocked to fail expects a score of 50 and eight "not checked" results
No-locate "Never return an address, workplace or location" The invariant test over every people-search fixture
Never name a person from an AI guess "The model proposes; the code verifies against an evidence URL" A test that gives the model's guess with no evidence URL and expects no name in the report

A test is one way to enforce a rule in code, and the one this chapter teaches. Chapter 17 adds the others, such as checks that block a commit and checks that run on every pull request, and shows how to make sure the tests themselves can't be skipped.

Tell your agent

"Write an invariant test for the no-locate rule. Load every people-search fixture, run each through the report builder, and fail if the report contains any address, workplace or coordinate from the fixture, or any field named like address, street, employer, lat or lng. Add a fixture that has all of those so the test has something to catch. Run it and show me the result."

Tests as Instructions Your Agent Can't Forget

Chapter 4 explained that an agent forgets. Its context fills up, a new session starts fresh, and an instruction file is read but not always followed. An agent asked in March never to return an address may, in June, add a vendor field called last_known_city to a report because it seemed helpful. Nothing in the agent's process stops it.

A test changes that. A test as agent instruction is a test used to tell the agent what must stay true, in a form the agent runs and checks itself against on every change. The agent doesn't have to remember the rule. When it runs the tests and one fails with "report contains a location field: last_known_city," the agent is told exactly what it broke, in the moment, in its own working loop. Most coding agents run a project's tests on their own when the tests exist and the instruction file says to.

This only works if the agent may not change the tests to make them pass. An agent faced with a failing test and a goal of finishing the task will sometimes weaken the test, mark it skipped or delete it, then report success. That is the most important line to put in a project's instruction file about tests: never change, skip or delete a test to make it pass without asking first. Chapter 17 shows how to run the tests where nobody can skip them, so the rule doesn't depend on the agent's goodwill. A linter, a tool that reads code and flags risky patterns, can help too. Its rule called no-disabled-tests, which the ESLint plugins for Vitest and Jest both offer, fails the check when a test is quietly switched off with .skip. Chapter 17 covers linters.

Check Which Files Changed

Sawyer warning A weakened test and a fixed bug both end in "all tests pass." Before you accept a fix, ask the agent to list every test file it changed. Then read those changes first, looking for a loosened expect line or a new .skip.

Asking the Agent for Tests

Asking the agent for tests means giving the agent a test request specific enough that the tests it writes check what you care about. A vague request such as "add tests" gets tests of whatever was easiest, usually small functions that were already working. A good request names four things:

  1. The behavior. What must be true, in one sentence a member would understand.
  2. The cases. The normal case, and each way it could go wrong.
  3. The level. Unit, integration or end-to-end, and whether to send requests straight to the server.
  4. What not to mock. The code under test always runs for real. Only outside services get stand-ins.

Then ask the agent to list, in plain English, what each test checks before it writes any code. That list is short enough to read, and it's where you'll catch a missing case.

Test-Driven Development and the Failing Test First

Test-driven development, often called TDD, is a way of working where you write a test for a behavior before writing the code for it. Then you write just enough code to make the test pass, and repeat. The cycle is often called red, green, refactor: a failing test shows red, the passing test shows green, and then you tidy the code while the tests keep you safe.

You don't need to work this way all the time. One part of it is worth using every time you fix a bug or protect a rule. The failing test first rule says that before you trust a test, you must see it fail against the broken code. A test that has never failed has never proved it can catch anything. Agents write tests that pass on the first run all the time, and some of them would pass no matter what the code did. A test that checks the scheduler marked "some row" as sent passes on the broken code and the fixed code alike.

Here is the loop to ask your agent for, in order.

  1. Write the test for the bug or the rule.
  2. Run it against the current code and show it failing, with the failure message.
  3. Fix the code.
  4. Run it again and show it passing.
  5. Run all the tests, to show nothing else broke.

If step 2 passes, the test is wrong, or the bug isn't where you thought. Either way you've learned something before changing any code. A builder who sees "1 failed" and then "1 passed" has evidence. A builder who sees only "all tests pass" has a claim.

Tell your agent

"Add this rule to our project instruction file: 'Never change, skip or delete a test to make it pass without asking me first. For every bug fix, write a test that reproduces the bug, show me it failing, then fix the code and show me it passing.' Then follow that rule for the next fix."

Numbers That Mislead and Tests That Wobble

Test Coverage

Test coverage is the share of an app's code that runs at least once while the tests run, usually shown as a percentage of lines. Test runners can report it with a flag such as --coverage, and agents like to quote it: "coverage is now 82 percent."

The number tells you which code the tests never touch, which is useful. It can't tell you whether the code they do touch is checked. A line counts as covered when it runs, whether or not any expect line looks at what it did.

Coverage Is Not Safety

The idea that coverage is not safety means a high coverage percentage can still leave the parts that matter most untested. Coverage counts lines run, not risks checked. Suppose the dating-safety app has 82 percent coverage. The scoring function, the phone formatter and the results page components might be covered many times over. The payment webhook route is perhaps forty lines in an app of thousands, and leaving it out costs about one percent. The number barely moves, and the most expensive path in the app has no test.

Coverage can also be pushed up by tests that check nothing. A test that calls the report builder and checks only that it returned something runs every line of the builder, and it would pass with an address in the report.

The way to use coverage is as a map of blind spots. Ask which critical paths have zero coverage, not what the total is. The simulator below lets you spend a fixed budget of tests and watch the two numbers part ways.

Diagram: Coverage Versus Safety

Run the Coverage Versus Safety MicroSim Fullscreen

Coverage Versus Safety

Type: microsim sim-id: coverage-versus-safety
Library: p5.js
Status: Specified
Bloom Level: Evaluate
Bloom Verb: prioritize
Learning Objective: The learner will prioritize five tests from a list of twelve for the dating-safety app so that all four critical risks are covered, and judge why the choice with the highest line coverage leaves risks open.

Prerequisites: test coverage, coverage is not safety, critical user path, test the money path, test the auth path, invariant test (all defined in this chapter).

Evidence of Mastery: The learner commits a set of five tests. The set is correct when it covers all four critical risks (R1 to R4 in Content). Mastery is a correct set on the first or second attempt, plus the correct answer to the follow-up question. Watching the meters change while toggling tests is exploration.

Misconceptions: (1) Higher coverage means a safer app. (2) Testing the biggest files first is the best use of time. (3) A test that runs a line has checked it.

Instructional Rationale: Prioritizing under a fixed budget makes the learner weigh coverage against risk directly. Seeing two meters move in different directions as tests are picked makes the gap between them felt rather than told.

Content:

Critical risks:

  • R1. A member pays and gets no credits, or gets credited twice (money path).
  • R2. A member reads another member's scan, or a viewer changes data (auth path).
  • R3. A failed check is counted as passed (no false all-clear).
  • R4. A report reveals an address, workplace or location (no-locate).

Tests the learner can pick (budget: exactly 5):

# Test Coverage added (percentage points) Risk covered
1 Unit tests for the results page components 14 none
2 Unit tests for the phone and date formatters 6 none
3 Unit tests for the admin dashboard charts 12 none
4 Webhook integration tests (good, twice, forged, unknown member) 1 R1
5 Auth integration tests on every scan route 4 R2
6 All-vendors-down test expecting a score of 50 3 R3
7 No-locate invariant test over every fixture 2 R4
8 Report builder test that only checks a report was returned 5 none
9 Unit tests for the email templates 8 none
10 End-to-end test: sign in and upload a photo 9 none
11 Unit tests for the settings page 7 none
12 Scoring function test with eight passing results 4 none

Starting coverage with no tests picked: 30 percent.

Follow-up question: "Picking tests 1, 3, 9, 10 and 11 gives 80 percent coverage. Why is that set unsafe?" Options: A. It leaves all four critical risks untested (correct). B. 80 percent is too low; it should be 90. C. Unit tests never count toward safety. D. End-to-end tests are always flaky.

Provenance: The four risks come from research/seed-notes.md (webhook untested, routes untested, no false all-clear, no-locate needing a test). Coverage numbers are illustrative and must be labeled "illustrative numbers."

Rules: Coverage shown = 30 + the sum of picked tests' coverage points. Risks covered = the union of picked tests' risks, shown as 0 to 4. Exactly five tests must be picked before Check is enabled. A set is correct when risks covered = 4; the only correct set is 4, 5, 6, 7 plus any one other test. Tests 8 and 12 cover no risk: test 8 checks nothing about addresses, and test 12 has no failed checks in its input. The highest-coverage set is 1, 3, 9, 10, 11 at 80 percent with 0 risks covered. Tests 4, 5, 6 and 7 together give 30 + 1 + 4 + 3 + 2 = 40 percent; the fifth test adds 4 to 14 points, so every correct set lands between 44 and 54 percent.

Learner Activity:

  1. The learner sees twelve test cards, two meters (Coverage percent and Risks covered, 0 of 4), and a budget counter "0 of 5 picked."
  2. The learner toggles tests on and off. Both meters update at once.
  3. With five picked, the learner presses Check.
  4. If the set is wrong, the sim names each uncovered risk and allows one more attempt.
  5. After a correct set or two attempts, the follow-up question appears.

Feedback: Up to two attempts at the set. Correct: "All four critical risks are covered, at [n] percent coverage." Incorrect: "Uncovered: [list of risks]. Coverage is [n] percent." After the second wrong attempt, the correct four tests are highlighted. Follow-up: one attempt; correct answer A, with the message "Coverage counts lines run, not risks checked." Wrong answers show that message too.

Starting State: No tests picked, coverage 30 percent, risks covered 0 of 4. The prompt reads "You have time for five tests. Which five?"

Chapter Anchors: The chapter's example app has 82 percent coverage with the webhook untested. The webhook route is about forty lines and leaving it out costs about one percent.

Flaky Tests

A flaky test is a test that sometimes passes and sometimes fails when nothing in the code has changed. The usual causes are timing, shared data and real outside services. A browser test that waits a fixed two seconds for the score passes when the scan is quick and fails when it's slow. Two tests that use the same test member trip over each other when run at the same time. A test that calls a real vendor fails whenever the vendor has a bad minute.

Flaky tests do more harm than their number suggests. Once a test fails at random, people learn to rerun it until it passes, and soon they rerun every failure without reading it. Then a test that fails for a good reason gets rerun and ignored like the others. Agents pick up the same habit fast, and will report "the failure was flaky" about a failure that wasn't.

The fixes are the tools from earlier in this chapter. Wait for the score to appear on the page instead of waiting a fixed time. Give each test its own fixture data. Mock outside services. When a flaky test can't be fixed today, mark it as quarantined, with a note saying why and when it will be fixed. Keep it out of the set that blocks changes. Don't delete it, and don't let it fail at random in the middle of the tests everyone relies on.

Tell your agent

"Run the coverage report and show me, for each critical path (payments, sign-in and access, scoring when vendors fail, and no-locate), whether any test covers it. I don't need the total percentage. Then run all the tests five times and list any test that didn't give the same result every time, with its likely cause."

Back to Moving Day

The two roommates didn't test every drawer. They tried the lock, the shut-off valve and the stove, because those would hurt if they were wrong, and each gave a clear answer in a minute.

Tests do the same for an app built with an agent. The money path and the auth path are the locks. The no-false-all-clear and no-locate tests are the shut-off valve. Each gives a clear pass or fail in seconds, and each keeps working after the agent has forgotten why it mattered. The drawers can wait.

The Locks Are Tested

Sawyer celebrating You can now pick the first tests for any app: the money path, the auth path and each product rule, every one seen failing before you trust it. Chapter 11 goes into the database, where the scheduler bug lived.

Key Takeaways

  • Reproduce a bug before fixing it, and fix it at the root cause, not the symptom.
  • Manual testing suits looks and taste. Automated tests, run by a test runner, suit anything that must hold after every change.
  • Unit, integration and end-to-end tests cover one function, pieces working together and a whole journey. A smoke test checks the app is alive after a deploy.
  • Test critical user paths first. In the dating-safety app, the payment webhook and the route modules had no tests.
  • A regression test keeps a fixed bug fixed. An invariant test makes a product rule, such as no-locate, a rule enforced in code that the agent can't forget.
  • See a test fail before you trust it. Coverage is not safety, and a flaky test teaches everyone to ignore failures.

See Annotated References