Lesson 20 of 40Quality loops
Testing with AI
Get AI to write tests that catch real bugs, judge the tests it writes, and verify UI with Playwright and a browser-driving agent.
AI tools are very good at writing tests, and very good at writing tests that prove nothing. A test suite is the one thing that tells you, without trusting anyone's opinion, whether AI-written code works. So the tests have to be better than the code they check. This lesson shows how to ask for tests first, how to spot a useless test in seconds, and how to check real user interfaces with Playwright, both as a repeatable test suite and with an agent clicking through a live browser.
Tests are the agent's eyes
A model cannot see whether your app works. It can only read text: code, error messages, command output. A test is a small program that runs your code with known inputs and checks the outputs, then prints pass or fail. That turns "does it work?" into text the model can read and act on.
This is why the official Claude Code guidance says to give Claude a way to check its work: tests, a build, a linter, a screenshot to compare. Without one, the agent is guessing. With one, it can run the check, read the failure, and fix the code on its own. In the build, test, review loop from the previous lesson, tests are the gate everything else depends on.
Test-first prompting
The strongest pattern is test-first: describe the behaviour with examples, have the AI write tests that fail, confirm they fail, and only then ask for the implementation. It works because the tests are written before any code exists, so they describe what you want rather than what the code happens to do.
A good test-first prompt looks like this:
Add a `parse_price` function in pricing.py. Do NOT implement it yet.
Write pytest tests in tests/test_pricing.py for these cases:
- "$4.99" -> 499 (cents, as an int)
- "4" -> 400
- " $1,250.00 " -> 125000
- "" and "abc" -> raise ValueError
- "-3.00" -> raise ValueError (no negative prices)
Run the tests and show me they fail. Then stop and wait.Then, in a second message: "Now implement parse_price until all tests pass. Do not change the tests." That last sentence matters. When an AI cannot make code pass, a common shortcut is to quietly edit the test to match the broken code.
Put test-first prompting in order.
- Tap the steps below in the right order.
Judging AI-written tests
Before trusting a generated test, ask one question: would this test fail if the code were wrong? If you cannot picture the bug it would catch, it is decoration.
Common ways AI tests go wrong:
- Asserts nothing real.
assert result is not Noneor "the function returns a string" passes for almost any bug. - Mirrors the implementation. The test recomputes the answer using the same logic as the code, so a bug in the logic appears in both and they agree.
- Mocks everything. If the database, the clock and the function under test are all replaced with fakes, the test only checks the fakes.
- Snapshot spam. A snapshot test saves the whole output and fails if anything changes. Hundreds of them get updated blindly, so they stop catching anything.
- Happy path only. Empty input, invalid input and the error branch are where bugs live.
Run this. The function has a bug. One test catches it and one does not.
Press Run (⌘ Enter) to see what happens.The weak test passes on broken code. The strong one names an exact expected output, so the bug cannot hide. Ask your AI for tests that state exact expected values for concrete inputs.
total_with_tax(price): assert total_with_tax(100) == 100 * 1.2. The code computes price * 1.2. What is wrong with the test?Coverage, the share of code lines your tests execute, is a useful signal and a poor goal. A test can run every line and assert nothing. Use coverage to find untested files, then judge the tests by the bugs they would catch.
Playwright: testing the real UI
Unit tests check functions. They cannot tell you that the Sign up button is hidden behind a cookie banner. End-to-end (E2E) tests drive a real browser through your app the way a user would: open a page, type, click, check what appears.
Playwright is a widely used open source library for this. It controls Chromium, Firefox and WebKit (the engine behind Safari), and its test runner is the @playwright/test package. Setup in a JavaScript or TypeScript project:
npm install -D @playwright/testnpx playwright install # downloads the browsersHere is a realistic test for a sign-up form, assuming your dev server runs on port 3000:
import { test, expect } from "@playwright/test";
test.describe("sign up", () => {
test("creates an account and greets the user", async ({ page }) => {
await page.goto("http://localhost:3000/signup");
await page.getByLabel("Email").fill("ada@example.com");
await page.getByLabel("Password").fill("correct-horse-battery");
await page.getByRole("button", { name: "Create account" }).click();
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Welcome, ada");
});
test("shows an error for a short password", async ({ page }) => {
await page.goto("http://localhost:3000/signup");
await page.getByLabel("Email").fill("ada@example.com");
await page.getByLabel("Password").fill("abc");
await page.getByRole("button", { name: "Create account" }).click();
await expect(page.getByRole("alert")).toBeVisible();
await expect(page.getByRole("alert")).toHaveText("Password must be at least 8 characters");
});
});Notice how it finds elements. getByRole and getByLabel look for things the way a user or a screen reader does: "the button named Create account", "the field labelled Email". They do not depend on CSS classes or the page structure, which AI tools rewrite freely. A side effect: if Playwright cannot find your field by its label, the field probably has no proper label, which is an accessibility bug worth fixing. Also, expect on a locator waits and retries until the condition is true or a timeout passes, so you do not need manual sleeps.
Run the suite with:
npx playwright testIt runs every *.spec.ts file, prints which tests passed, and gives a detailed report for failures. Check the official docs for the current configuration options, such as starting your dev server automatically and running headed so you can watch.
- my-app/
- playwright.config.tsbrowsers, base URL, dev server
- package.json@playwright/test as a dev dependency
- src/
- tests/
- signup.spec.tsone file per user flow
- checkout.spec.ts
Letting the agent drive a browser
There is a second, faster way to check UI. Claude Code can drive a real browser itself: started with claude --chrome, it uses the Chrome integration to open pages, click, fill forms and take screenshots, then compares what it sees with what you asked for.
You ask for a UI change and how to check it.
The two approaches do different jobs:
Match each check to what it is best at.
Use the agent for discovery and the Playwright suite for protection. A good closing prompt: "Check the change in the browser, then write a Playwright test for the flow you just checked."
Running tests in CI
CI (continuous integration) runs your checks automatically on a server for every push or pull request. Tests that only run on your laptop are tests that get skipped. A typical CI job installs dependencies, runs npx playwright install, starts the app, and runs npx playwright test, failing the pull request if anything is red. Many teams add an AI reviewer in CI too, such as the Claude GitHub action covered in the capstone lesson. The rule stays the same: a red check blocks the merge, whoever wrote the code.
- test-first
- Writing failing tests from examples before writing the code that makes them pass.
- end-to-end test
- A test that drives the whole app through a real browser, the way a user would.
- Playwright
- An open source library and test runner (@playwright/test) that automates Chromium, Firefox and WebKit.
- locator
- A Playwright description of how to find an element, such as getByRole or getByLabel.
- snapshot test
- A test that saves an output and fails when it changes; easy to over-use and update blindly.
- coverage
- The share of code your tests execute. A signal for gaps, not proof the tests check anything.
- CI
- Continuous integration: a server that runs your checks automatically on every push or pull request.