Plain Reckoner
English
← The blog

Testing

Your AI-Written Test Keeps Flaking. Stop Adding Sleeps.

Stop adding sleeps to flaky AI-written tests. Find the failing state, inspect a trace, isolate test data and check whether the fix actually worked.

By Plain Reckoner Team · Release date: 2026-11-01

Selected source checked:

How do you fix a flaky AI-written test? Reproduce the failure, identify the condition the test depends on, and wait for that observable condition instead of adding an arbitrary delay.

A browser test passes on your laptop, fails in the build system, and passes when you run it again. The coding agent responds by adding a delay. The next failure produces another delay. Soon the test is slower, the failure is still there, and nobody can explain what the test is waiting for. The useful question is not how long to wait. It is what observable condition should make the next action valid.

This guide walks through a practical investigation of an intermittent browser test. The example is a fictional document editor with a Save button, an asynchronous request, and a confirmation message. It is not a benchmark result or an experiment run by Plain Reckoner. You can adapt the process to your own application, but each change needs evidence from your own failing run.

The official Playwright guidance supports testing visible behavior, isolating test state and using assertions that wait for the intended condition. Its trace viewer helps inspect recorded actions. Those are tool capabilities and testing practices; they do not establish that a particular AI model always writes flaky tests. The rest of this guide is an editorial workflow for applying those ideas without treating a retry as proof that a defect has been fixed.

In this guide
  1. A quick reproduction record
  2. Keep the failing run before changing anything
  3. Write the expected user journey in plain language
  4. Check what the selector really identifies
  5. Replace guessed time with an observed condition
  6. Find state shared between tests
  7. Check the environment before blaming the model
  8. Read the trace as a sequence of evidence
  9. Ask the agent for one change and one prediction
  10. Verify the fix without cherry-picking a pass
  11. Keep retries as a diagnostic signal
  12. Leave a useful handoff for the next failure

A quick reproduction record

Record the test name, environment, failure message and trace for an actual failing run. Repeat under the same conditions, then change one suspected cause and check whether the original failure can still occur. A retry that passes is a signal to investigate, not proof that the test is fixed.

Keep the failing run before changing anything

Start by saving the evidence you already have. Record the test name, command, browser, environment, relevant revision and final exit status. Keep the failure message and any trace or screenshot that the runner produced. If the process never reached an assertion, record that separately. A browser launch failure is a different problem from a Save button that never becomes enabled.

Ask the agent to describe the earliest observable difference between the passing and failing runs. Do not begin with a large rewrite. If the agent changes selectors, timeouts, fixtures and application behavior together, a later pass will not explain which change helped. You want a small hypothesis that can be checked, not a collection of plausible edits that happen to produce a green run.

For the document editor example, the first useful fact might be that the test clicks Save while the document is still loading. Another possibility is that the request succeeds but the test looks for an old notification. A third is that the setup creates a document with a name already used by another test. All three can produce a failure near the same line. The line number alone does not identify the cause.

Write the expected user journey in plain language

Before inspecting the generated code, write the behavior you actually need to verify. A useful version might be: open a document owned by the signed-in user, wait until it is editable, change its title, save it, and confirm that the saved title survives a reload. That description gives the test an external target. It does not depend on the current class names or the agent's preferred implementation.

Now separate the journey into meaningful states. The editor is ready. The title has changed locally. The save request has been accepted. The stored title is visible after a new read. These states are related but not interchangeable. A toast might prove that the interface displayed a message; it may not prove that the intended document was stored with the intended value.

Keep the test proportionate to its purpose. A small component test may deliberately stop at the local state change. An integration test may check the request contract. An end-to-end test may check persistence. The problem is not that every test must exercise everything. The problem is claiming that a narrow check proves a broader user outcome than it actually observes.

Find the state, not another sleep
01
Keep the failed trace
02
Name the ready state
03
Isolate test data
04
Recheck the failure

Check what the selector really identifies

A generated selector can look precise while depending on an accidental detail. Consider a button selected as the third item in a list. It may work until a new toolbar action appears. A long chain of CSS classes can be similarly brittle. The selector captures how the interface happened to be built, rather than which control the user intended to activate.

Prefer a stable relationship to the user-visible control when the framework supports it. Review the accessible role and name, the relevant form label, or another deliberate testing contract. A role-based selector still needs scope. If both a dialog and the underlying page contain a Save button, a broad query may be ambiguous or target the wrong context.

Ask the agent to explain why the selector should match exactly the intended element. If it answers only that the selector currently matches, the reasoning is incomplete. Check how it behaves when a menu is open, a dialog is present, a loading state is active or another document is visible. These variations help distinguish a robust selector from one that merely fits the screenshot used to generate it.

Replace guessed time with an observed condition

A fixed sleep says that the next step should probably be ready after a chosen duration. It does not say what readiness means. On a fast machine the delay wastes time; on a slower run it may still be too short. Increasing the number can conceal the symptom without making the test sensitive to the state it actually needs.

For the editor, a meaningful condition could be that the title field is enabled and contains the loaded value. After saving, a meaningful condition could be a visible saved state followed by a fresh read of the changed title. Choose the condition that corresponds to the claim under test. Waiting for an unrelated spinner to disappear may be insufficient if the editor has several independent loading operations.

Do not replace every sleep mechanically with a different wait call. Inspect the relationship between the action and the condition. A notification left over from an earlier action can make a waiting assertion pass too early. A network response for another document can do the same. The check needs enough identity to connect the observed result to this particular operation.

Find state shared between tests

Intermittent failures often become clearer when you inspect what the tests share. Look for account state, storage, cookies, document names, database records, temporary files and server configuration. A test that passes alone but fails in a group has given you a useful clue. It may depend on order or collide with another test's work.

In the fictional editor, two workers might both create a document called Draft and then edit whichever matching row appears first. Slowing the tests down will not make the identity rule correct. Give each test deliberate ownership of its data, and use the actual identifier returned by setup where appropriate. The exact mechanism depends on the application, but the principle is to remove accidental ambiguity.

Cleanup also needs scrutiny. A broad deletion at the end of one test can remove another test's record. A failed test may never reach its cleanup step. Prefer setup and teardown that clearly identify their own resources, and inspect what happens when the test aborts halfway through. Do not give a test suite access to unrelated production records just to make setup convenient.

Check the environment before blaming the model

An AI-written test can fail because it is wrong, but the surrounding environment can fail too. Confirm that the server is ready, the required environment variables are present, the browser can launch and the expected network paths are reachable. Do not print secret values while checking configuration. Presence and intended configuration are usually enough for the first diagnostic step.

Compare versions as well as commands. A local browser, dependency tree or operating system may differ from the build worker. Record those differences instead of saying only that the test works locally. A dependency update can change timing, behavior or defaults. A reproducible setup makes a later comparison more meaningful than another screenshot of a green result.

If the environment prevents the test from reaching the application, say so plainly. The test has not passed, but neither has it demonstrated an application defect. Keep infrastructure failures distinct from failed behavioral assertions. That distinction prevents the agent from changing correct application code to compensate for a missing browser executable or a server that never started.

Read the trace as a sequence of evidence

A trace is most useful when you ask a specific question. Did the expected page load? Which element did the click target? Was the document already editable? What happened immediately after the action? Work forward from the last state that you can explain, rather than jumping straight to the final error and guessing backward.

For the editor example, compare the state before the click with the state after it. If the title field was disabled, investigate readiness. If the request used the wrong document identifier, investigate setup and selection. If the request succeeded but the new title disappears on reload, investigate persistence or a stale read. Each observation points to a different layer of the workflow.

Keep traces private when they contain application data. A trace can include page content, request details or other sensitive material. Sanitize a reproduction before sharing it with a hosted tool, public issue or outside reviewer. A useful bug report does not need your customer's document, session token or full internal environment to explain a timing or identity problem.

Ask the agent for one change and one prediction

A useful instruction is to identify the suspected cause, propose the smallest correction, and say what should change in the evidence if the hypothesis is right. For example, the agent may predict that waiting for the editor's ready state will eliminate clicks made before document loading completes. That is more informative than a general request to make the test stable.

Review the diff before running the test. Check whether the agent weakened the assertion, skipped the failing path, caught an error without reporting it or replaced a real interaction with a direct internal state change. Those edits may make the test pass while removing its purpose. Require a clear explanation when the test's scope changes.

Preserve the old failure evidence alongside the proposed correction. If the original run failed because of a duplicate document name and the patch only changes a timeout, the mismatch should be visible. A prediction that cannot be checked against an observable result is not yet a strong diagnostic hypothesis. Narrow it until the evidence can distinguish it from a competing explanation.

Verify the fix without cherry-picking a pass

After the focused change, run the relevant test under the conditions associated with the failure. If parallel execution mattered, include that condition. If a slow request exposed the problem, use a controlled way to represent that delay in an appropriate test environment. Repeating the same easy local case may provide little evidence about the original failure.

Record the full result, including failed attempts. A single pass after several failures is not a clean verification. At the same time, a small number of repeated passes does not prove that an intermittent issue can never return. Describe what was exercised and what remains untested. The goal is evidence proportional to the claim, not a magic repetition count.

Then check nearby behavior affected by the change. A new readiness condition might wait forever when loading fails. A more specific selector might no longer work in a different legitimate state. The most useful follow-up checks are those connected to the changed assumption. Do not expand into an unrelated full rewrite simply because the agent can generate more tests.

Keep retries as a diagnostic signal

Retries can help you gather evidence about intermittent behavior, but they should not erase the first failure. Preserve the original attempt and make flaky outcomes visible in the results you review. If the pipeline marks a retried pass as an uncomplicated success, the team may stop noticing a test that increasingly depends on luck.

Distinguish test retries from application retries. A test runner starting a fresh attempt is different from the application repeating a save request. The latter may have side effects, such as creating two records or sending two notifications. Your test should make that behavior visible when it is relevant to the requirement, rather than assuming every repeated action is harmless.

If you temporarily quarantine a flaky test, give the decision an owner, a reason and a condition for restoring coverage. Quarantine is an operational choice, not a fix. Keep another appropriate check for the important behavior where possible. Otherwise a quieter dashboard may conceal the fact that the user journey is no longer being checked at all.

Leave a useful handoff for the next failure

A good final note states the symptom, the cause supported by the evidence, the change and the completed verification. It also names unresolved conditions. For example: the test selected a shared document name; setup now returns a unique document identifier; the failing parallel scenario completed successfully; the external identity provider was represented by a fixture and was not tested live.

Save the minimal reproduction or sanitized fixture when it is useful. Link the relevant test and the evidence instead of pasting an enormous log into the summary. A later maintainer should be able to see what behavior the test protects and why the readiness condition exists. Without that context, a future agent may remove the condition as unnecessary complexity.

Finally, compare the final artifact with the original goal. The outcome is a test that checks the intended behavior under understood conditions, not merely a green icon. If the cause remains uncertain, preserve that uncertainty and the next useful observation. An honest incomplete diagnosis is more useful than a confident claim that another arbitrary sleep solved the problem.