Arezgitfield notes / engineering
Developer toolsUPDATED OCT 28, 2026

Test Time-Dependent Code with Controlled Clocks

Separate clock readings from scheduled callbacks, test exact time boundaries, and use fake timers without hiding cancellation, cleanup, or integration behavior.

Arezgit Editorial6 min read
AREZGIT / FIELD NOTEDEVELOPER TOOLS
A timeout test that sleeps for real can be slow and still fail when the machine is busy. Freezing the current date alone may not fix it, because reading time and scheduling a callback are di
READ / VERIFY / APPLYTECHNICALLY REVIEWED

A timeout test that sleeps for real can be slow and still fail when the machine is busy. Freezing the current date alone may not fix it, because reading time and scheduling a callback are different behaviors. Identify which kind of time the code uses, then control the relevant boundary explicitly.

The examples use Vitest 4 to distinguish an expiry comparison from a scheduled callback and to verify cancellation. A local fake clock can make those assertions deterministic. Database expiry, broker leases, and network behavior still require checks against the component that owns their clock.

Separate wall-clock rules from elapsed-time rules

Identify whether the feature depends on a calendar instant, a duration, or a scheduled callback. A certificate-like expiry rule compares an instant with an expiry value. A debounce schedules work after inactivity. A performance measurement needs an elapsed-time source whose behavior matches that purpose.

Write the business boundary in plain language. In a synthetic invitation feature, the invitation becomes invalid at its recorded expiry instant. Decide whether equality counts as expired and use the same rule across the authoritative validation paths.

Prefer injecting a clock or scheduler through a narrow interface when that makes the dependency explicit. This allows a pure business calculation to receive a known instant without globally replacing every timer used by the test runner or its dependencies.

Keep the trusted time source clear. Changing the browser's local clock should not authorize a server-protected invitation. Unit tests can verify the client display, while authoritative expiry tests must exercise the server or native boundary that makes the actual decision.

Test immediately before, at, and after the boundary

Choose fixed synthetic instants rather than calculating expectations from the real date during the assertion. Test a value just before expiry, exactly at expiry, and just after. The point is to distinguish the intended comparison, not merely show one valid and one invalid day.

Include malformed or missing timestamps in the input-validation tests. Define the accepted serialization and reject ambiguous input at the authoritative boundary. A local display format should not quietly become the protocol representation used for authorization or persistence.

Calendar features need additional cases chosen from their actual rules. A daily report scheduled in a named timezone differs from a duration measured as elapsed seconds. Test daylight-saving transitions and timezone conversion where the product supports those semantics instead of assuming that adding one calendar day always means a fixed number of seconds.

Keep those tests separate from timer execution. A function deciding whether an invitation is expired may need only a controlled current instant. Starting a scheduler in that test adds state and cleanup without improving evidence about the comparison.

Advance scheduled work deliberately

Here is a complete small Vitest 4 test file for a one-shot reminder. Save it in a disposable test project that already has Vitest 4 installed and run it with that project's normal test command. The reminder returns an explicit cancellation function; the tests exercise both the deadline and cancellation.

import { afterEach, expect, test, vi } from "vitest";

function scheduleReminder(send: () => void, delayMs: number): () => void {
  if (!Number.isFinite(delayMs) || delayMs < 0 || delayMs > 2_147_483_647) {
    throw new RangeError("Invalid reminder delay");
  }
  const timer = setTimeout(send, delayMs);
  return () => clearTimeout(timer);
}

afterEach(() => {
  vi.clearAllTimers();
  vi.useRealTimers();
});

test("sends once when the delay elapses", async () => {
  vi.useFakeTimers();
  const send = vi.fn();
  scheduleReminder(send, 1_000);
  await vi.advanceTimersByTimeAsync(999);
  expect(send).not.toHaveBeenCalled();
  await vi.advanceTimersByTimeAsync(1);
  expect(send).toHaveBeenCalledTimes(1);
  expect(vi.getTimerCount()).toBe(0);
});

test("cancellation removes pending work", async () => {
  vi.useFakeTimers();
  const send = vi.fn();
  const cancel = scheduleReminder(send, 1_000);
  cancel();
  expect(vi.getTimerCount()).toBe(0);
  await vi.advanceTimersByTimeAsync(1_001);
  expect(send).not.toHaveBeenCalled();
});

The first test distinguishes 999 milliseconds from the boundary at 1,000. The second checks that cancellation removes the timer before cleanup runs, then verifies that the side effect stays absent past the deadline. If the assertion only ran after afterEach cleared everything, the test could conceal a leaked timer.

This helper deliberately accepts a synchronous callback and schedules one timer. It is not a durable reminder service or an async job runner. If sending returns a promise, define who observes its rejection and whether cancellation can stop work that already started. Those requirements change the implementation and its tests rather than being solved by advancing the clock farther.

The Vitest 4 utility reference distinguishes vi.setSystemTime from timer advancement. Changing the mocked system time does not itself fire scheduled callbacks. Use the timer controls that correspond to the behavior under test.

For a synthetic debounce, assert that the callback has not run before the delay, then advance through the boundary and assert the intended result. Add a second input before the deadline and verify that the earlier scheduled work is canceled or superseded according to the feature's contract.

When callbacks schedule promises or additional timers, account for that execution model. Use the supported asynchronous advancement mechanism when the test needs to observe promise work between scheduled callbacks. Avoid assuming that one synchronous clock jump completes every asynchronous operation.

Do not drain all timers indiscriminately when the feature contains a recurring interval. Choose a bounded number of steps or a specific time advance that proves the intended transition. Otherwise a test can spend its effort executing an artificial infinite schedule rather than checking the feature.

Restore time and verify cleanup after failure

Install fake timers before the operation whose scheduling they need to control. Restore real timers in cleanup that runs after both success and assertion failure. In Vitest 4, vi.useRealTimers provides that restoration boundary.

Review module initialization. Code that captures a time source or creates an interval at import time can escape a later mock or leak work across tests. Prefer an explicit start-and-stop lifecycle for services that own timers, and verify that stopping cancels their outstanding work.

Test cancellation separately from ordinary completion. Start the delayed operation, cancel it, advance beyond its original deadline, and assert that no side effect occurs. Also verify that associated resources are released and no new timer is scheduled after cancellation.

Avoid sharing global fake-time state across concurrently running tests unless the runner provides suitable isolation. A test changing the clock while another test reads it can create the same nondeterminism the mock was supposed to remove. Use scoped dependencies or a supported isolated test arrangement.

Keep real integration evidence for external timing

Fake timer success does not establish that a database TTL feature, broker lease, or network timeout behaves the same way. Those components have their own clocks and scheduling. Add bounded integration checks at the boundaries the application actually relies on.

For the invitation feature, test the authoritative expired response and verify that the interface presents a useful recovery action. For a retrying request, verify cancellation and total elapsed budget with a controlled dependency, using the retry design guide to define the operation contract.

If a test hangs under fake time, investigate which dependency is waiting on a timer or clock outside the expected control. Do not fix the symptom by adding arbitrary real sleeps throughout the suite. Reduce the fixture until the time dependency is visible, then choose the appropriate controlled or integration test.

Add an assertion that would fail if the intended time boundary moved. For an expiry check, equality may be the decisive case; for the reminder above, execution at 999 milliseconds or execution after cancellation is wrong. Keep the relevant external integration check alongside these fast tests so that changing a local clock cannot conceal a failure in the component that actually owns time.

READER SIGNAL

Was this guide useful?

Your rating helps us prioritize clearer, more practical technical content.

AREZGIT / DESKTOP WORKSPACEFROM FIELD NOTE TO RELEASE

Review diffs, run checks, and prepare the release in Arezgit.

Keep Git review, security scanning, API checks, database inspection, and release preparation together in one local desktop application.

Explore Arezgit