TestClock
Controllable Clock service for tests.
Instead of waiting for real time to pass, effects that use Effect.sleep, timeouts, schedules, retries, and other time-based operators can be driven by advancing the test clock. This makes time-based tests deterministic and fast. The module also includes helpers for moving test time, temporarily using the live clock, and warning when a test appears to be waiting on time without advancing it.
Constructors
Signature
declare const make: (...args: [options?: Options]) => Effect<
{
adjust: (duration: Input) => Effect<void, never, never>;
currentTimeMillis: Effect<number, never, never>;
currentTimeMillisUnsafe: () => number;
currentTimeNanos: Effect<bigint, never, never>;
currentTimeNanosUnsafe: () => bigint;
monotonicTimeNanos: Effect<bigint, never, never>;
monotonicTimeNanosUnsafe: () => bigint;
setTime: (timestamp: number) => Effect<void, never, never>;
sleep: (...args: [duration: Duration]) => Effect<void, never, never>;
withLive: <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, Exclude<R, never>>;
},
never,
Scope
>;Layers
Models
A TestClock simplifies deterministic and efficient testing of effects that involve the passage of time.
Details
Instead of waiting for actual time to pass, sleep and methods implemented in terms of it schedule effects to take place at a given clock time. Use adjust and setTime to move clock time, and all effects scheduled to take place on or before that time will automatically run in order.
Gotchas
Calls to sleep and methods derived from it will semantically block until the time is set to on or after the time they are scheduled to run. Fork the effect being tested, then adjust the clock time, and finally verify that the expected effects have been performed.
Signature
interface TestClock extends Clock {
adjust(duration: Input): Effect<void>;
setTime(timestamp: number): Effect<void>;
withLive<A, E, R>(effect: Effect<A, E, R>): Effect<A, E, R>;
}Other
Testing
Accesses a TestClock instance in the context and increments the time by the specified duration, running any actions scheduled for on or before the new time in order.
Signature
declare function adjust(duration: Input): Effect<void>;Sets the current clock time to the specified timestamp. Any effects that were scheduled to occur on or before the new time will be run in order.
Signature
declare function setTime(timestamp: number): Effect<void>;testClockWith
Retrieves the TestClock service for this test and uses it to run the specified workflow.
Signature
declare function testClockWith<A, E, R>(
f: (testClock: TestClock) => Effect<A, E, R>,
): Effect<A, E, R>;Executes the specified effect with the live Clock instead of the TestClock.
Signature
declare function withLive<A, E, R>(effect: Effect<A, E, R>): Effect<A, E, R>;
Creates a
TestClockwith optional configuration.