How to speed up tests for AI coding agents
By Flavio
Updated
Tagged: AI
How to shorten an agent's feedback loop with focused tests, realistic boundaries, useful failures, and broader checks before shipping.
A coding agent can edit a function quickly and then spend far longer waiting to find out if the change works.
When that feedback is slow, every correction gets expensive. The agent edits a file, runs the checks, waits, reads the error, and tries again, so a small misunderstanding can drag through several rounds. I wrote about wrapping that loop by putting a retry limit in a state machine.
Before you spin up more agents or switch models, look at that loop first. You want a check that directly answers the question blocking the work right now, whether that’s a single test or a run against the app and a real database.
Useful feedback starts with a precise question
Say an agent is fixing a bug in a task manager web app where archived tasks still show up in search.
You can describe the behavior you want without mentioning any implementation details. An archived task shouldn’t show up in normal search, it should stay in the archive, and restoring it should bring it back to search results. I wrote more about specifying outcomes like this in What teaching can tell us about prompting.
Right away, those rules give you a small set of checks to run, with no reason to touch unrelated parts of the app like the settings screens.
Testing whether a filtering helper got called doesn’t help much here. Code can call that helper with the wrong argument, or another layer can put the archived task right back into the response.
Start at the narrowest place where the bug shows up, like the search query or the API response. Create the task in its archived state, run the check, and verify the real output.
Keep cheap decisions close to the code
Plenty of rules can be tested without booting the whole app. If the logic that decides which tasks match a search lives in one function, you can feed it a few explicit inputs and check what comes back.
Here’s a search.js module with that logic:
export function searchTasks(tasks, query) {
return tasks.filter((task) => !task.archived && task.title.includes(query))
}
And here’s search.test.js, testing it with the Node.js built-in test runner:
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { searchTasks } from './search.js'
const tasks = [
{ title: 'Write the launch email', archived: true },
{ title: 'Update the home page' },
{ title: 'Write the release notes' },
]
test('search skips archived tasks', () => {
const titles = searchTasks(tasks, 'Write').map((task) => task.title)
assert.deepEqual(titles, ['Write the release notes'])
})
test('search matches part of the title', () => {
const titles = searchTasks(tasks, 'home').map((task) => task.title)
assert.deepEqual(titles, ['Update the home page'])
})
Make sure the test imports the real function from your module. If you copy the filter expression into the test file, you end up maintaining two versions of the same rule, and the app can break while the test stays green.
If you have to boot the entire app just to reach one piece of logic, inspect its dependencies before introducing a new abstraction. Pulling out a small helper function can make the rule easy to test directly, while other times a focused integration test is simpler. Either way, when the archive rule changes, the failure should point straight to that rule.
Test the boundary that could be wrong
If you swap out the database for a fake that already returns the records you expect, a unit test won’t catch a broken query.
Agents fall into this trap all the time when you ask them to add tests. They wire up an elaborate mock, call the handler, and prove nothing except that the handler returns whatever the mock handed it.
For the archived task bug, write at least one check that runs the real query against a test database. Insert both visible and archived tasks, run the query, and check the returned IDs. Skip the browser and user login flow if the query doesn’t depend on them.
Match the test boundary to the bug you’re chasing. A disabled button needs a browser, a permission check needs the server’s real authorization path, and an export bug might mean opening the generated file to inspect what’s inside.
Give the agent a focused command
Make your test entry points easy to find. If the only command in your docs boots every service and runs the full suite, an agent will run that every time, or worse, guess a command that skips half the checks it thinks it ran.
Write down three things in AGENTS.md or your README, right next to the dev setup: how to run a single test file, how to test a wider feature area, and which checks must pass before a task is done.
With the Node.js test runner, node --test discovers and runs every test file in the project:
node --test --test-reporter=spec
Here’s the output from that run:
✔ search skips archived tasks (1.027208ms)
✔ search matches part of the title (0.057959ms)
ℹ tests 2
ℹ suites 0
ℹ pass 2
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 63.446333
You can narrow it down by passing a file path and --test-name-pattern to run only the matching tests:
node --test --test-reporter=spec --test-name-pattern="archived" search.test.js
That produces a smaller run:
✔ search skips archived tasks (1.009542ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 63.082666
When you only have two tests in one file, the speedup is invisible, but the same command pattern keeps runs fast once a codebase grows to hundreds of test files.
If you’re using Vitest, where tests import from vitest, you can filter by file name, line number, or test name, as shown in Vitest’s filtering guide:
npx vitest run search
npx vitest run search.test.js:11
npx vitest run -t "archived"
Pass the file path along with a name filter whenever you can. With only a name filter, Vitest still has to execute every test file just to see which tests match.
Have the agent report the exact files or patterns it ran, since “tests passed” means very different things for one file versus the whole suite.
Focused checks and release checks serve different moments
While the agent is fixing the bug, you want fast feedback on the specific behavior it’s changing. Before you accept the work, you need to check what sits around it, because an archive fix can break archive counts, restore flows, or pagination even when the original bug test passes.
Widen the checks in stages: reproduce the bug, fix it, run tests for the related area, and then run the project’s required checks.
Scale the checks to the risk of the change. Tweaking a UI label doesn’t need the same proof as rewriting a search query, and a quick copy change doesn’t need a new test suite.
Ask the agent to explain why it picked those checks based on what could break. “Search and archive share the query, so I checked both” tells you whether the coverage makes sense, whereas a raw list of commands gives you no context.
If another change merges before yours lands, re-run the checks on the combined code so you’re testing what’s going out, not an older snapshot. Here’s how that progression fits together:
Work through one repair from failure to acceptance
Let’s walk through a concrete example. Suppose search shows one result per page, and your test database has three tasks matching “Write”, ordered newest first:
| Task | State |
|---|---|
| Write the launch email | Archived |
| Write the release notes | Visible |
| Write the pricing page copy | Visible |
Your first focused check runs the real search query for page one and expects “Write the release notes”. Right now the broken query returns the archived launch email instead, so you have a clean reproduction of the bug.
An agent might try a shortcut and filter out archived tasks from the response after fetching page one. The archived task vanishes, sure, but now page one comes back empty because the two visible tasks sit further down in the database, past the slice the query grabbed.
Your acceptance test needs to spell out what the user should see. With a page size of one, page one should return the release notes, page two should return the pricing page copy, and any total count in the UI should read two. That catches the half-baked fix right at the query layer, without spinning up a browser.
While editing, the agent keeps rerunning this small query test suite until it passes. Next, widen out to the archive query and restore logic: the launch email should stay in the archive, and restoring it should return it to search in whatever position the app’s sort order puts it.
After that, run the browser flow that ties everything together: archive a search result, search again, open the archive, and restore the task. That verifies the frontend sends the right request and renders the updated list.
Finish by running the project’s required checks on the full change, and keep the query tests, browser flow, and broader suite separate in the report. If the browser test fails, the passing query test helps narrow down where the problem is, and you know the fix isn’t ready to ship yet.
Keeping the dataset this small makes every expected result obvious. You save time by catching bad fixes on the first query test instead of booting the whole app over and over.
Measure the waiting before optimizing it
A slow test run often wastes time where you least expect it. The assertions themselves might finish in milliseconds while every run rebuilds the app, downloads dependencies during setup, or hangs on a failing network request waiting to time out.
Look back at the two node --test runs above: both finish in about 63 milliseconds total, yet each individual test takes one millisecond or less. On a tiny file, almost the entire runtime is just Node booting the test runner.
Check your runner’s timing output and split setup time from actual test execution. Fix the slowest unnecessary step first, then measure again under the same conditions to confirm it helped.
Measure cold and warm runs separately, too. A warm local cache can make repeated runs feel snappy while every fresh CI job still pays the full setup penalty, so always note whether a number came from a cold or warm run.
Fast tests shrink the edit-and-check loop that agents repeat over and over. Once that loop is quick, any remaining slowdown usually sits outside the test suite, like unclear requirements or slow code review.
Parallel tests need separate state
Running tests in parallel speeds things up when the checks are independent and your machine has room to spare. It also exposes hidden coupling fast: if two tests share an account and one deletes a task the other expects to find, both pass on their own and fail randomly side by side.
In browser tests, Playwright provides isolated browser contexts so every test gets its own cookies and browser storage. You still have to isolate the backend, though, because two separate browser sessions can still collide on the same database row.
Give each test its own unique records, or an isolated database when the setup allows it. Every test should create the data it needs instead of expecting an earlier test to leave it around.
Agents get tripped up hard by order-dependent tests. When a failure disappears the moment you run that test by itself, the agent burns retries chasing a phantom bug when the real fix is clearing out the shared state.
Sharding helps after the suite can run independently
Once a test suite grows large enough, you can split it across multiple machines. That’s called sharding, and Playwright’s configuration lets you run one slice of the suite per job.
Whether sharding pays off depends on how evenly the tests split and how much setup each machine has to repeat. If one shard gets stuck with a long end-to-end flow while the others finish early, the whole pipeline still waits on that single job. And if every shard spends most of its time booting an expensive environment, adding more machines just multiplies that overhead.
Check how test runtimes are distributed before you crank up the shard count. For a small app, one machine and a focused test command are plenty, so wait until you measure a real bottleneck before taking on the maintenance cost of distributed runs.
Browser tests should act on what the user sees
Browser tests break for the wrong reasons when they tie themselves to your HTML structure. If a test finds the archive button through a long chain of CSS classes, a harmless layout tweak turns it red, and the agent burns time fixing the test even though the flow still works.
Follow Playwright’s best-practice guide: test what the user sees, and pick locators by role and accessible name.
Open the task list, find the archive button by its accessible name, click it, and check the updated list. Checking only that a component rendered skips the behavior you care about.
Headless runs work well for repeatable checks, though you’ll still want to open the app yourself whenever you change visual layout, keyboard navigation, or how an editing flow feels.
Make failures explain what happened
An agent fixes bugs much faster when the failure message points straight at the problem. Seeing “Expected true, received false” forces it to guess what broke and dig through the code from scratch.
Here’s the start of what the focused run prints when the !task.archived check is missing from searchTasks():
✖ search skips archived tasks (1.922167ms)
ℹ tests 1
ℹ suites 0
ℹ pass 0
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 64.803709
✖ failing tests:
test at search.test.js:11:1
✖ search skips archived tasks (1.922167ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
[
+ 'Write the launch email',
'Write the release notes'
]
Right away, the test name tells you which rule failed, and the diff points to the exact task that shouldn’t be in the list. Comparing the list of titles with deepEqual instead of asserting on a boolean gives the agent real context to work with.
Do the same for browser failures by keeping traces or screenshots. One look tells you if a button was missing, a network request failed, or the app landed on the wrong page. Just make sure your logs describe what went wrong without printing test credentials.
Make your test runner separate code failures from environment failures, too. If the local database never started, you want the output to say that up front instead of blaming the archive test.
When a test turns flaky, avoid hiding it behind silent retries. Re-running until it turns green hides the original bug and makes it harder to trust your suite later. Track down why it failed, or flag it clearly as uncertain.
Keep the expected behavior independent
An agent can easily write an implementation and a test that both agree on the wrong behavior.
Suppose it decides that archiving a task should delete it, and then writes a test confirming the task disappears from search. The code and the test agree, so the suite stays green, yet you still broke the requirement that users can restore archived tasks later.
Write down the expected behavior before you review the code. Even two sentences describing what the user does and what should happen next give you an independent check against whatever the agent built.
When you’re reviewing a bug fix, check that the regression test fails on the old code and passes after the fix, just like the failing run above. Seeing it fail first confirms it catches the bug you fixed.
And for small, low-risk changes, pause and ask if a new test is worth keeping around. Sometimes the existing suite plus a quick manual check is plenty. Agents can spit out new tests in seconds, but you’re the one who has to maintain every extra test on future changes.
Find the slowest useful check
Start with the last change where an agent sat around waiting on tests. Look at which check held it up, what signal you got back from it, and whether a smaller test could have answered the same question faster while the final run still checked the surrounding code.
Fix that one bottleneck first. Document the focused command, strip out setup steps it doesn’t need, and tighten the failure output so it’s easy to read. If you want to go deeper into structuring checks across functions, databases, and CI, the free Testing, Debugging & CI/CD Handbook walks through those tradeoffs in detail.
Run the agent through that faster path on your next change and time it. Those numbers will tell you if you need more test tooling or if that single fix was enough.
Want me to talk about your product? You can sponsor this site.
Related posts about ai: