The short answer: Test-driven development (TDD) is one of the best ways to work with AI coding assistants, because tests give the AI a precise, checkable definition of "done." Write or review the test cases yourself first, have the assistant turn them into runnable tests, confirm they fail, let the assistant implement until they pass, then refactor with the tests as a safety net. The rule that matters most: the tests are the contract, so the AI may change the implementation but must not weaken or delete tests to make them pass.
AI coding assistants are fast and fluent, and that's exactly the problem. They produce plausible code quickly, and plausible code is easy to accept without noticing that it handles the happy path and nothing else. Developers who've used these tools for a while learn to distrust output that hasn't been verified.
Test-driven development turns that weakness into a workflow. In TDD you write a failing test, make it pass with the simplest implementation, and then clean up. When an AI writes the implementation, the tests become the specification it has to meet, and a machine-checkable one at that. The assistant can iterate as many times as it needs; it's done when the tests pass, and not before.
This guide walks through a practical TDD loop with AI assistants such as GitHub Copilot, Claude Code or Cursor. The approach is tool-neutral: what matters is who decides what the tests are, and how you stop the AI from gaming them.
TDD and AI suit each other
Three properties make the pairing work well.
- Tests remove ambiguity. A prompt like "handle invalid input" leaves the AI to guess what invalid means. A test that says "an empty email returns a 400 with error code EMAIL_REQUIRED" doesn't.
- Agents can check their own work. Tools that can run commands, such as agent modes in editors and terminal agents, can run the tests after each change and keep going until they pass, instead of stopping when the code merely looks right.
- Tests catch regressions in AI edits. AI assistants sometimes change more than you asked. A good suite catches the unintended change before review does.
The flip side is that the AI is now optimising to make tests pass, so the quality of your tests sets the quality of the result. Weak tests produce code that passes weak tests.
Step 1: decide the test cases yourself
The most important step is the one you shouldn't delegate. Before any code exists, write down the behaviour you expect as a list of cases. Use the AI as a brainstorming partner to find cases you missed, but make the decisions yourself, because the test list is the specification.
Suppose you're building a function that applies discount codes to a shopping cart. Your list might start like this:
- A valid percentage code reduces the subtotal by that percentage.
- A valid fixed-amount code reduces the subtotal by that amount, never below zero.
- An expired code is rejected with a clear reason.
- A code with a minimum spend is rejected when the subtotal is below it.
- Codes are case-insensitive.
- Only one code can be applied; applying a second replaces the first.
- Amounts are rounded to two decimal places using the project's rounding rule.
Then ask the assistant: "Here are the cases for applyDiscount. What edge cases am I missing?" Good suggestions often include unknown codes, codes limited to certain products, currency handling and what happens with an empty cart. Add the ones that matter; ignore the rest. You now have a specification that a human has thought about.
Step 2: turn the cases into runnable tests
Now let the assistant write the test code from your list. This is a task AI handles well: translating clear cases into the syntax of your test framework. Give it the case list, the function signature, and an example of an existing test file in your project so it matches your conventions.
import { describe, it, expect } from "vitest";
import { applyDiscount } from "./discounts";
const cart = (subtotal: number) => ({ subtotal, currency: "USD" as const });
const today = new Date("2026-06-01");
describe("applyDiscount", () => {
it("applies a percentage code", () => {
const result = applyDiscount(cart(200), "SAVE10", today);
expect(result).toEqual({ ok: true, total: 180, discount: 20 });
});
it("never takes a fixed-amount discount below zero", () => {
const result = applyDiscount(cart(15), "FLAT25", today);
expect(result).toEqual({ ok: true, total: 0, discount: 15 });
});
it("rejects an expired code with a reason", () => {
const result = applyDiscount(cart(100), "SUMMER24", today);
expect(result).toEqual({ ok: false, reason: "EXPIRED" });
});
it("rejects a code below its minimum spend", () => {
const result = applyDiscount(cart(30), "BIG50", today);
expect(result).toEqual({ ok: false, reason: "MINIMUM_NOT_MET" });
});
it("treats codes case-insensitively", () => {
expect(applyDiscount(cart(200), "save10", today)).toEqual(applyDiscount(cart(200), "SAVE10", today));
});
});
Review these tests line by line. This is where AI-written tests most often go wrong: assertions that check the wrong thing, expected values copied from what the code would produce rather than what it should produce, or tests that pass trivially. Check each expected value by hand. Notice that the date is passed in rather than read from the system clock, so the tests are deterministic.
Step 3: watch the tests fail
Run the tests before writing any implementation and confirm they fail for the right reason: the function doesn't exist yet, or returns the wrong value. This step catches tests that can't fail, such as an assertion that compares a value with itself, which would otherwise pass forever without testing anything. It takes seconds and is easy to skip; don't.
Step 4: let the AI implement until the tests pass
Now hand over the implementation, with a clear instruction about the contract:
Implement applyDiscount in src/discounts.ts so that all tests in
src/discounts.test.ts pass. Discount codes are defined in src/discount-codes.ts.
Rules:
- Do not modify the test file. If you believe a test is wrong, stop and explain why.
- Keep the function pure: no network, no reading the system clock.
- Run the tests after each change and continue until they all pass.
An agent that can run commands will iterate on its own: write code, run tests, read failures, fix, repeat. An assistant without command access needs you to run the tests and paste failures back, which still works, just more slowly.
The instruction "do not modify the test file" is the heart of this workflow. Without it, an assistant facing a stubborn failure may "fix" the test instead of the code: loosening an assertion, adding a skip, or deleting the case. If it thinks a test is wrong, it should say so, and you decide. Put this rule in your project instruction file so it applies to every session, and check for test changes in every review.
Step 5: refactor with the tests as a safety net
Once the tests pass, ask for improvements: clearer names, removing duplication, extracting the rounding rule into a shared helper. Because the behaviour is pinned down by tests, refactoring is safe: if a change breaks something, a test fails immediately. This is also a good moment to ask the assistant to review its own implementation for edge cases the tests don't cover, which may lead you back to step 1 with new cases.
Finding the gaps in your tests
Coverage reports, read critically
Coverage tools show which lines your tests execute. Ask the assistant to read a coverage report and propose tests for uncovered branches. Treat the suggestions with care: coverage shows what code ran, not whether behaviour was checked. A test that executes a line without asserting anything meaningful raises coverage without adding safety.
Mutation testing
Mutation testing tools, such as Stryker for JavaScript and TypeScript, make small changes to your code (flipping a comparison, removing a line) and check whether your tests notice. A surviving mutation means a gap in your tests. These reports pair well with an AI assistant: give it a surviving mutation and ask for a test that would kill it. It's a direct, measurable way to strengthen a suite.
Property-based tests
For functions with clear invariants ("the total is never negative," "the discount never exceeds the subtotal"), property-based testing libraries generate many inputs automatically. Ask the assistant to identify invariants and write properties for them. They often find edge cases neither you nor the AI thought of.
Integration and end-to-end tests
Unit tests are where TDD with AI works most smoothly, but the same loop applies higher up. For an API endpoint, write tests that call the endpoint with real HTTP requests against a test database: valid input, invalid input, unauthenticated, unauthorised, and the not-found case. For a critical user flow, write an end-to-end test in a browser automation tool describing what the user does and sees.
These tests are slower, so the AI's iteration loop is slower too. Keep the end-to-end suite small and focused on flows that would be most damaging if broken, and let unit tests carry the detailed cases.
Making it work for a team
- Write the rules down. Your project instruction files should say how to run tests, that tests must not be weakened without approval, and where test files live. Every assistant on the team then follows the same contract.
- Review test changes separately. In pull requests, look at test diffs first. A change that edits both the code and its tests deserves the most scrutiny.
- Keep the suite fast. An agent can run a 10-second suite after every edit; a 10-minute suite makes it guess. Invest in speed.
- Fix flaky tests immediately. A flaky test teaches both people and agents to ignore failures, which defeats the purpose.
- Make CI the final judge. Whatever happens locally, the full suite runs in CI on every pull request, and failures block merging. The guide to AI coding agents in CI covers how to automate safely.
Common mistakes
- Letting the AI write both the tests and the code without review. It will make them agree, which isn't the same as being correct.
- Accepting expected values without checking them. If the expected output came from running the code, the test proves nothing.
- Skipping the red step. Tests that never failed may not be able to fail.
- Testing implementation details. Tests tied to internal structure break on every refactor and make AI-assisted refactoring painful. Test behaviour through public interfaces.
- Non-deterministic tests. Real clocks, random values and network calls make failures intermittent. Inject them, as the example does with the date.
A worked example: adding a rule with the loop
To see the whole loop on a change rather than a new function, suppose the business adds a rule a month later: discount codes can be limited to first-time customers. Here's how the change flows.
Cases first. You add to the list: a first-time-only code applies when the customer has no previous orders; it's rejected with FIRST_ORDER_ONLY when they have one; existing codes without the restriction behave exactly as before. You ask the assistant for missed cases, and it suggests cancelled and refunded orders. That's a genuine product question, so you check with the product owner, who decides that only completed orders count. That decision goes into the cases as well.
Tests next. The assistant adds four tests to the existing file, following its style. You check each expected value and notice one test passes an order history with a cancelled order but expects a rejection, which contradicts the decision you just made. You correct it. This is the review step earning its keep: the mistake would otherwise have become the specification.
Red. The new tests fail because the function doesn't take an order history yet. The existing tests still pass.
Green. The assistant changes the signature to accept the customer's completed-order count, updates the callers, and implements the rule. It runs the whole suite, not just the new tests, and one older test fails because a caller wasn't updated. It fixes the caller rather than the test, as instructed.
Refactor. With everything passing, you ask it to move the eligibility checks into a small list of rule functions, so the next rule is a one-line addition. The tests confirm nothing changed.
The entire change is small, reviewable and fully covered, and the order-history decision is recorded in a test where nobody can forget it.
Testing code that calls AI models
Many applications now include features that call a language model, and TDD needs adapting for them, because model output varies between runs. Split the feature into two kinds of tests.
Deterministic tests for your code. Prompt construction, parsing of the model's response, validation, retries and error handling are ordinary code. Test them with a fake model client that returns fixed responses, including malformed JSON, refusals, empty responses and timeouts. These tests are fast, stable and follow the normal TDD loop.
Evaluations for the model's behaviour. Whether the model gives good answers is checked differently: with a set of realistic inputs and criteria for a good output, scored across many examples rather than asserted on one. The guide to testing LLM features with evals covers how to build these. Run them when prompts or models change, not on every commit.
Mixing the two causes trouble. Unit tests that call a real model are slow, cost money and fail randomly, which teaches everyone to ignore failures. Keep the model out of unit tests, and keep quality judgement in evaluations.
Keeping test suites fast enough for agents
An agent might run your tests dozens of times during one task, so speed directly affects how well AI-assisted TDD works. A few habits keep suites quick:
- Keep unit tests free of I/O. No network, no real database, no file system where avoidable. Pure functions test in milliseconds.
- Run a focused subset during development. Tell the agent the command for running one file or one test pattern, and save the full suite for before committing and for CI.
- Use a real database only where it matters. Integration tests for queries and permissions are worth it; spinning up a database for logic that could be tested purely is not.
- Parallelise. Most modern test runners run files in parallel. Make sure tests don't share state, so parallelism is safe.
- Delete tests that no longer earn their place. Duplicate or obsolete tests slow everything down and add noise to failures.
Put the fast and full test commands in your project instruction file, so every assistant uses the right one at the right time.
Prompts that work well in the loop
A handful of prompts cover most of the TDD loop. Saving them as reusable commands or snippets makes the workflow quick to repeat:
- Finding cases: "Here is the behaviour I want and the cases I have. List edge cases I've missed, grouped by input validation, boundaries, error handling and concurrency. Don't write code."
- Writing tests: "Turn these cases into tests in the style of [existing test file]. Expected values must come from the cases, not from running code. Keep tests deterministic."
- Implementing: "Make these tests pass without modifying them. Run the tests after each change. If a test seems wrong, stop and explain."
- Refactoring: "Improve the structure of this code without changing behaviour. Run the full test suite after each step."
- Strengthening: "Here is a surviving mutation from the mutation testing report. Write a test that fails with the mutation and passes without it."
Cases where strict TDD is the wrong fit
TDD works best when you know what the behaviour should be. Some work doesn't start there. Exploratory prototypes, where you're still discovering what to build, and visual design work, where "correct" is judged by eye, fit the loop poorly. Forcing tests first in those cases mostly produces tests you'll throw away.
A practical compromise is to explore freely with the AI assistant, decide what to keep, and then apply the loop before the code becomes permanent: write down the cases the prototype revealed, turn them into tests, and let the assistant rebuild or harden the implementation against them. You get the speed of exploration and the safety of tests, without pretending you knew the answers before you started.
Similarly, for one-off scripts and throwaway tooling, a quick manual check may be enough. Reserve the full loop for code that other people and systems will depend on, which is most production code. The question to ask is simple: if this behaviour changed silently next month, would anyone be hurt? If yes, it deserves a test.
A quick checklist for each change
- ☐ Cases written or reviewed by a person, including edge cases the assistant suggested
- ☐ Expected values checked by hand, not copied from running code
- ☐ New tests seen failing before implementation
- ☐ Implementation done without modifying tests
- ☐ Full suite passing, not just the new tests
- ☐ Refactoring done with tests green after each step
- ☐ Test diffs reviewed first in the pull request
Seven boxes take a minute to check, and they catch nearly every way AI-assisted TDD goes wrong.
Over time, the checklist becomes second nature, and the test suite it produces becomes one of the most valuable assets in the codebase: a precise, executable description of how the system behaves, which every future change, human or AI-assisted, can rely on.
Frequently asked questions
Can AI write unit tests for me?
Yes, AI assistants are good at turning clear test cases into runnable test code in your framework. You should still decide which behaviours to test and check every expected value yourself, because AI-written tests often assert the wrong thing or copy what the code currently does rather than what it should do.
How do I stop an AI assistant from changing my tests to make them pass?
Tell it explicitly not to modify test files and to explain any test it believes is wrong instead, put that rule in your project instruction file so it applies to every session, and review test diffs first in every pull request. Changes to both code and tests in the same change deserve the closest scrutiny.
Is test-driven development still worth it with AI coding tools?
It's arguably more valuable. Tests give AI tools a precise, machine-checkable definition of done, agents can run them to verify their own work, and they catch unintended changes that AI edits sometimes introduce. The human effort shifts toward deciding the right test cases.
What is mutation testing and how does it help with AI-written code?
Mutation testing makes small deliberate changes to your code and checks whether the tests fail. Changes that survive reveal gaps in the tests. Giving a surviving mutation to an AI assistant and asking for a test that catches it is a direct way to strengthen a test suite.
Which AI coding tool is best for TDD?
Tools that can run your test command and read the results work best, because they can iterate until tests pass on their own. Agent modes in editors and terminal agents such as Claude Code can do this. The workflow matters more than the specific tool.
The takeaway
AI assistants write code quickly; tests make sure it's the right code. Decide the cases yourself, let the assistant turn them into tests and then into an implementation, watch the tests fail before they pass, and never let the AI move the goalposts by editing tests. With that discipline, TDD turns an AI assistant from a fast source of plausible code into a fast source of verified code.
Author at LuminaryEra
The LuminaryEra editorial desk publishes long-form, hands-on guides on AI-assisted development, large language models, developer tools and web engineering. Articles are researched and drafted with the help of AI tools, link to their sources, and are corrected when readers report errors.
View all articles


