Direct answer
Control the clock and the random source at the boundary of the test, make every timer advance explicit, and restore state after each case. Jest documents timer mocks for controlling timeout behavior, and Vitest documents fake timers with explicit advancement methods such as runAllTimers and advanceTimersByTime. Seeding random inputs and recording the chosen values turns an unreproducible output into one a reviewer can compare.
Determinism is not the same as correctness. A frozen clock makes a result repeatable, and it says nothing about whether the expected value is the right one. The goal is to remove uncontrolled variables so a failure means the behavior changed, while keeping the meaningful boundary cases, such as a date rollover or a timeout, still exercised deliberately.
State restoration is the part that gets skipped and causes the next suite run to fail. A test that installs fake timers and never restores them hands the simulation to whatever runs next. Treat the restore step as part of the control, not as cleanup to remember later.
Why uncontrolled time and randomness cost real time
An uncontrolled clock turns a logic bug into an intermittent one. A test that reads the current date can pass all day and fail at midnight, at a month boundary, or in a time zone the author did not consider. The failure then looks like flakiness, and the investigation starts in the wrong place. Pytest lists uncontrolled system state among the candidate causes of flaky tests, which is the same class of problem seen from the outside.
Uncontrolled randomness is worse in one specific way: it can hide the case that would have failed. A generated input that exposes a boundary condition may never be produced again, so the failure cannot be reproduced and cannot be fixed. Seeding the generator and recording the value converts that into an ordinary reproducible failure.
Both problems are expensive at exactly the wrong moment, which is during review of a change. The flaky tests triage guide covers what to do when a test already fails intermittently. This post covers the earlier move: remove the uncontrolled variables so the flake never forms.
Evidence and its limits
Official, F007: Jest timer mocks document controlling timeout behavior in tests. Use that to justify installing fake timers for a specific test. The exact defaults and API surface are framework-version specific.
Official, F008: Vitest timers document fake timers plus explicit advancement methods such as runAllTimers and advanceTimersByTime. This supports advancing the clock deliberately rather than waiting. The Vitest timer API reference describes the enabling function. Exact behavior depends on the installed version.
Derived, F009: Seed random inputs, record the chosen values, and restore shared state after each test. Jest’s snapshot testing guide recommends controlling non-deterministic values. The full workflow described here is a general testing recommendation, not a framework feature.
Official: The Pytest flaky tests page lists uncontrolled system state and thread-safety issues as candidate causes of non-deterministic behavior. Hypothesis documents how generated inputs are constrained by the strategies supplied, which bounds what a seeded run can and cannot show.
Nothing here claims deterministic tests establish correctness, and no benchmark for the technique is cited. Framework behavior is kept framework-specific on purpose: Jest’s timer API and Vitest’s timer API are not interchangeable.
Locate time and randomness dependencies
The first step is finding where the uncontrolled inputs enter. A dependency is any place the code reads something the test does not own: the current date or time, a random value, a timeout duration, an interval, a monotonic counter, or a value derived from an ID generator.
Two techniques find most of them. A search for the obvious calls in each language and framework, such as clock and random functions, produces a candidate list quickly. A failing test with a value in the assertion that nobody wrote by hand is the other signal: timestamps, generated identifiers, and long decimal fractions usually mean an uncontrolled source reached the output.
| Dependency | Where it enters | Control point | Restoration step |
|---|---|---|---|
| Current date or time | Direct clock read, or a library default | Install fake timers at the test boundary | Restore real timers after the case |
| Timeout duration | Timer or scheduler setup | Freeze timers, then advance explicitly | Restore real timers after the case |
| Random value | Random generator or UUID generator | Seed the generator, or inject a source | Reset the generator to its default |
| Monotonic counter | ID or sequence generator | Inject a sequence source | Reset the counter |
| System locale or zone | Formatting that reads the environment | Set the zone explicitly for the test | Restore the environment setting |
The table deliberately names the restoration step for every row. That column is the one that prevents the next test from inheriting the simulation, and it is the column most often left blank.
Choose the correct clock abstraction
A frozen clock is a control, and the choice of where to install it determines what the test can express. Installing fake timers inside the code under test couples the test to an implementation detail. Installing them at the test boundary, with the code receiving its clock as a dependency, keeps the test honest about what it controls.
The framework documentation supports the boundary approach indirectly. Jest’s timer mocks behind F007 control the timers the runtime exposes. Vitest’s fake timers behind F008 do the same for their runtime. Neither documentation claims that freezing timers models every promise or thread interleaving, and the async races guide treats scheduling as a separate control from the clock.
Three clock choices cover most cases:
| Choice | What it controls | When to use it | Cost |
|---|---|---|---|
| Frozen at a fixed instant | Every timer and date read | Output depends on a specific time | Cleanup required, async code may stall |
| Frozen, then advanced | Timers plus elapsed time | Timeouts, retries, intervals | Each advance must be deliberate |
| Injected clock | Only what the code asks for | Code accepts a clock dependency | Requires a seam in the code |
The third choice is the most durable and the most work. A clock passed in as a dependency can be replaced by a fake in tests and by the real clock in production, and the test never has to reach into the runtime. Where that seam does not exist, fake timers at the boundary are the practical option, and the restoration step is not optional.
Do not freeze every clock in a suite without checking side effects. Some libraries schedule their own work on timers, and freezing the clock can prevent cleanup, logging, or a connection refresh from ever running. The official documentation behind F007 and F008 describes the control; it does not promise that frozen timers are safe in every codebase.
Advance timers deliberately
An advanced timer is an assertion about time. A specific advancement amount states that the behavior should have happened by then, and advancing too far can silently skip a boundary the test meant to check.
Vitest’s documented advancement methods behind F008 separate two intents. Running all timers executes every queued timer until the queue is empty, which is useful when the exact ordering does not matter. A specific duration moves the clock that far and no further, which is what a boundary test needs. Jest’s timer mocks behind F007 support the same shape of control for timeouts.
Deliberate advancement means naming the duration in the test and connecting it to a requirement. A retry that fires after thirty seconds should be tested by advancing thirty seconds, not by advancing an hour and checking that something happened. The second version passes whether the retry fired early, late, or three times.
| Scenario | Fixed input | Timer action | Expected observable result |
|---|---|---|---|
| Retry after a timeout | Deadline of 30 seconds | Advance exactly 30 seconds | One retry issued |
| Debounced handler | Delay of 250 milliseconds | Advance 249, then 1 | Handler fires once, after the full delay |
| Session expiry | Expiry at 1 hour | Advance 59 minutes, then 2 more | Session valid, then expired |
| Recurring poll | Interval of 5 seconds | Advance 15 seconds | Three polls recorded |
The debounced case shows why advancing in two steps matters. Going straight to 250 milliseconds proves the handler fired. Stopping at 249 first proves it had not fired yet, which is the boundary that makes the debounce correct.
Asynchronous cleanup deserves its own caution. Hiding a pending promise behind a timer advance can make a test pass while the cleanup never ran, and the failure reappears later as a leak or a warning. The fixtures isolation guide covers naming cleanup ownership so that a timer-based test cannot quietly skip it.
Seed and record random inputs
A seeded generator produces the same sequence on every run, which turns generated inputs into fixed inputs the reviewer can reason about. Seeding without recording the value is only half the work: a future reader needs to know which sequence the test used.
Two levels of control are worth having. The first is an explicit seed written in the test, so the sequence is fixed and reproducible. The second is an injected source, where the code asks for randomness through a dependency and the test supplies a stub that returns chosen values. The injected source is stronger because the test states the exact value rather than relying on a sequence position.
The distinction between controlling a value and covering a case matters here. A seed makes one run repeatable. It does not prove that the boundary cases in a class of inputs are covered. The property tests guide covers the complementary approach: state an invariant and let bounded generation search for the input that breaks it, with the failing example saved. Seeding and property generation solve different problems, and a seeded test is not a substitute for a stated invariant.
Record the seed and the values alongside the test. A comment naming the seed is enough for a reviewer; the recorded value is what makes a later failure diagnosable rather than mysterious. The snapshot review guide makes the same point about stored output: a recorded artifact only helps when someone reads it.
Reset state between tests
Restoration is where determinism work usually fails. A test that installs fake timers and forgets to restore them leaves the runtime in a simulated state, and the next test either stalls waiting for a timer or behaves as though time never passes. The failure appears in a test that has nothing to do with the clock.
Three habits prevent it. Install the control in a setup step and restore it in the matching teardown, so the pairing is structural rather than remembered. Give each test a fresh boundary for anything mutable, including the generator state and the clock. Run the suite in a randomized order locally before trusting it, because a fixed order can hide a restoration gap for years.
| Control installed | Restoration obligation | Symptom if skipped |
|---|---|---|
| Fake timers | Restore real timers | Next test hangs or never advances |
| Seeded generator | Reset to the default source | Later randomness tests depend on sequence position |
| Injected clock | Restore the production clock | Production path tested against a frozen instant |
| Set timezone or locale | Restore the environment | Formatting tests fail outside the author’s machine |
| Stubbed ID generator | Restore the real generator | Duplicate IDs in unrelated tests |
The fixtures isolation guide develops this in full, including varying test order before increasing parallelism. Isolation is also a precondition for parallel runs, since shared mutable state that is invisible in serial execution becomes a failure under concurrency. The flaky tests triage guide covers the investigation when a restoration gap has already produced intermittent failures.
Keep real-time boundary tests separate
Some behavior is about real time, and replacing the clock removes the thing being tested. A timeout that must eventually fire, a session that must expire, a rate window that must reset: these are contracts about elapsed time, and a frozen clock can only approximate them.
Keep two layers. Deterministic tests assert the logic at controlled boundaries: advance exactly to the deadline and check the transition. A small number of real-time checks assert that the machinery itself works with the real clock, typically with generous margins so they are not themselves flaky. The deterministic layer catches logic errors quickly. The real-time layer catches the case where the abstraction does not match the runtime.
| Deterministic test | Real-time check | Reason for keeping both |
|---|---|---|
| Advance to the deadline, retry fires | Real timeout fires within a generous margin | Logic versus actual timer machinery |
| Freeze at expiry, session rejected | Real session expires after the configured lifetime | Boundary logic versus configured duration |
| Advance three intervals, three polls | Real interval produces roughly the expected count | Counting logic versus interval scheduling |
The real-time checks should be few, slow-tolerant, and clearly separated, so a slow machine does not turn them into flakes. A margin that is too tight creates exactly the intermittent failure this post is trying to remove.
Review deterministic output with Claude Code
Deterministic tests fit the pass-or-fail loop described in the official best practices guidance. Give the agent the test, the fixed inputs, and the expected observable result, and ask it to run the test and report the command and exit status. Determinism makes that loop trustworthy, because a rerun is comparing like with like.
Review the proposed control for two specific problems. The first is a control installed too broadly, such as freezing every timer in a file rather than the ones the test needs. The second is a missing restoration step, which passes the test and breaks the next one. Both are easy for a reviewer to miss when the diff looks small and the run is green.
The agent can also help locate dependencies before any test changes. Ask for a list of clock and random reads in a named file, then verify each one. A candidate list from search is a lead to check, not a complete inventory, and a missed dependency is what produces the next intermittent failure.
When the output is a stored artifact rather than a plain assertion, the snapshot review guide covers reading the delta before accepting it. Deterministic output makes that review meaningful, because the delta reflects a behavior change rather than noise.
Document the remaining timing assumptions
Determinism removes uncontrolled variables from the test. It does not remove the assumptions the code makes about time, and those assumptions still need to be written down where the next engineer can find them.
Assumptions worth recording include the configured timeout durations and what happens when they are exceeded, the boundaries that were deliberately tested such as expiry and rollover, the timezone or locale the deterministic tests assume, and any real-time check that is allowed a generous margin. A short list next to the tests is enough. The point is that a reader can tell which time-related behavior was asserted and which was left to production.
The remaining gap should be honest. A test that advances exactly to a deadline proves the boundary logic and says nothing about whether the configured duration is appropriate for production load. That is a separate decision, and the complexity refactor guide and the static analysis baseline guide cover the adjacent quality work rather than this timing question.
Worked example: a retry with a deadline
Suppose a client retries a failed request after a 30-second deadline and gives up after three attempts. The existing test sleeps and checks the outcome, and it fails on slow machines because the sleep is shorter than the deadline under load.
The deterministic version installs fake timers at the test boundary, advances exactly 30 seconds, and asserts that one retry was issued. Stopping at 29 seconds asserts that no retry has fired yet, which is the boundary. Three steps of 30 seconds assert the give-up behavior.
| Executed step | Fixed input | Timer action | Observed result |
|---|---|---|---|
| Before the deadline | Deadline 30 seconds | Advance 29 seconds | No retry issued |
| At the deadline | Deadline 30 seconds | Advance 1 more second | One retry issued |
| After three retries | Three deadlines | Advance 30 seconds three times | Give-up recorded, no fourth attempt |
Each step restores the timers afterwards. The restoration is what lets the next test in the file run against the real runtime. The concrete win is a retry boundary that fails when the logic changes and passes when it does not, in milliseconds rather than sleep-bound seconds. The concrete loss is that the test no longer proves the real timer machinery fires in a real process, which is why a single real-time check with a generous margin is kept alongside it.
Stop conditions and follow-up
Stop and reconsider when making a test deterministic requires changing production behavior, because the test may be asserting something the code does not actually promise. Stop and reconsider when the frozen clock prevents necessary asynchronous work from completing, since the deterministic version may be hiding a real dependency. Stop and reconsider when a seed is the only thing standing between the suite and a failure, because a single seed is one point in a wide input class.
Follow-up comes in three forms. A restoration gap found during review should be fixed before the suite runs again, not scheduled. A newly deterministic test that still fails has found a real behavior change, and the flaky tests triage guide is the wrong next step because the failure is no longer intermittent. A boundary that cannot be expressed with the available clock control may need the injected-clock seam, which is a code change worth scoping separately.
For the wider practice around these tests, select checks for changed code places deterministic tests in the fast first tier, and isolate shared fixture state covers the boundaries that time control depends on. When the remaining gap is a class of inputs rather than a single boundary, property tests cover the search over that class.
Related workflow guides in this batch
Determinism is one control among several, and the neighbors cover the cases it does not. Triaging flaky tests is the next step when a test already fails intermittently. Isolating shared fixture state covers the boundaries that a clock or generator control depends on. Selecting checks for changed code places deterministic tests in the fast first tier of a run.
Failures caused by interleaving rather than elapsed time belong with making async scheduling deterministic. When the remaining gap is a class of inputs, property tests that generate edge cases cover the search over that class. A stored output needs the review method in snapshot diff review, and a check that ran but could not fail points at weak assertions found through mutation testing.
Evidence discipline is covered by a debug log of facts and hypotheses. Shrink a stubborn failure with minimal repro discipline. At the boundary between test and product, consumer-driven contract checks protect the interface the timers were hiding, and a suspected memory leak is investigated by comparing retained evidence across a fixed workload.
Beyond the testing lane, Git bisect for regression hunts locates the change that broke a previously deterministic test. Choosing a branch policy and defining merge checks decide whether these checks are enforced. Refactoring a hotspot that makes every test expensive is covered by complexity-driven refactoring.
Release work has its own verification questions. Deciding a semantic version increment follows from consumer impact rather than test count, tagging the reviewed candidate fixes which revision a deterministic run applies to, and a release checklist connects the checks that ran with the rollback unit. A broad suite that resists determinism is often a duplication problem, which is covered by choosing reuse or independence and baselining static-analysis noise.
Data gap and future update
No measured effect for deterministic tests appears in the source set. No reduction in flake rate, runtime, or escaped defects is claimed, and no benchmark is cited. The technique rests on framework documentation for timer control and on a derived workflow for seeding and restoration.
Framework APIs and defaults are version specific. Jest’s timer mocks behind F007 and Vitest’s advancement methods behind F008 were checked for reachability, and some referenced pages were not fully content-reviewed. A future update should add three things. Fresh content review of the timer APIs for the versions a reader is likely to run. A measured comparison of deterministic versus sleep-based tests on a real suite. A documented pattern for the injected-clock seam, since that requires a code change the documentation does not prescribe.
One AI API Key option for OpenAI-format agents
Claude Code uses an Anthropic-format route, so the One AI free model IDs are not a Claude Code model source. The packet records Claude IDs as unavailable on 2026-11-27.
For a separate OpenAI-format agent, One AI API Key offers https://api.oneaiapikey.com/v1, one key, and 46 live free IDs. That is a different client and request format, not a workaround for Claude Code authentication. Check the free model list and eligibility notes before choosing an agent route.
FAQ
Does making a test deterministic prove the behavior is correct?
No. Determinism makes a result repeatable. F007 and F008 document timer control, and F009 recommends seeding and restoring state. None of that validates the expected value. A deterministic test that asserts the wrong output passes confidently.
Should I freeze every clock in the suite?
Freeze the clocks a specific test needs, and check for side effects before freezing broadly. Some libraries schedule their own work on timers, and freezing the runtime can stop cleanup or connection maintenance from running. The restoration step has to be part of the same change.
Does a fixed seed cover all edge cases?
A seed fixes one sequence of values, which makes the run repeatable. It does not cover the boundary cases in the class of inputs the generator could produce. When the remaining risk is a class of inputs, state an invariant and use bounded generation as described in the property tests guide.
Are Jest and Vitest timer APIs interchangeable?
No. Jest documents timer mocks for controlling timeout behavior, and Vitest documents fake timers with methods such as runAllTimers and advanceTimersByTime. Keep the framework named in each test and do not assume one framework’s API or defaults apply to another.
Why do my deterministic tests still fail in the next file?
A control was installed without its restoration step. Fake timers left installed, a generator left seeded, or an environment variable left overridden all produce failures in unrelated tests. Restore each control in the matching teardown and run the suite in a randomized order locally to confirm.
More Claude Code troubleshooting
- Claude Code Dead Code: Prove Usage Before Removal
- Claude Code Git Stash: Recover Work Without Dropping It
- Claude Code Merge Conflicts: Resolve Behavior, Not Lines
- Claude Code Atomic Commits: Make Changes Revertible
- Claude Code Commit Messages: Encode Change Intent
- Claude Code Merge Queue: Recover Failed Groups
- Claude Code Hotfix Backports: Cherry-Pick Carefully
- Claude Code Rollback: Plan a Revert Before Release
- Claude Code Changelog: Write Consumer-Facing Changes
Sources
- Official: Jest timer mocks, supporting controlled timeout behavior in tests (F007).
- Official: Vitest timers, supporting fake timers plus
runAllTimersandadvanceTimersByTime(F008). - Official: Vitest timer API, reference for enabling fake timers.
- Official: Jest snapshot testing, supporting control of non-deterministic values in recorded output (F009).
- Official: Pytest flaky tests, supporting uncontrolled state and thread safety as candidate causes of non-determinism.
- Official: Hypothesis documentation, supporting the limits of generated and seeded inputs.