CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-jest--fake-timers

A comprehensive fake timer implementation for Jest that provides both legacy and modern timer mocking capabilities, enabling developers to control time flow in tests by mocking JavaScript's built-in timer functions.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

legacy-fake-timers.mddocs/

Legacy Fake Timers

Backward-compatible fake timer implementation with custom Jest timer control and precise execution ordering. This implementation provides deterministic timer behavior for tests that require the older Jest fake timers API.

Capabilities

Constructor

Creates a new LegacyFakeTimers instance with the specified configuration.

/**
 * Creates a new LegacyFakeTimers instance
 * @param options - Configuration object
 */
constructor<TimerRef = unknown>(options: {
  global: typeof globalThis;
  moduleMocker: ModuleMocker;
  timerConfig: TimerConfig<TimerRef>;
  config: StackTraceConfig;
  maxLoops?: number;
}): LegacyFakeTimers<TimerRef>;

Usage Example:

import { LegacyFakeTimers } from "@jest/fake-timers";

const fakeTimers = new LegacyFakeTimers({
  global: globalThis,
  moduleMocker: moduleMocker,
  timerConfig: {
    idToRef: (id) => id,
    refToId: (ref) => ref
  },
  config: stackTraceConfig,
  maxLoops: 100000
});

Timer Control

Use Fake Timers

Enables fake timers by replacing all timer APIs with mock implementations.

/**
 * Enables fake timers
 */
useFakeTimers(): void;

Use Real Timers

Restores the original timer implementations.

/**
 * Restores original timer implementations
 */
useRealTimers(): void;

Run With Real Timers

Temporarily executes a callback with real timers, then restores fake timers.

/**
 * Executes callback with real timers temporarily
 * @param cb - Callback function to execute
 */
runWithRealTimers(cb: Callback): void;

Usage Example:

fakeTimers.runWithRealTimers(() => {
  // This code runs with real timers
  setTimeout(() => console.log('Real timer'), 100);
});
// Fake timers are restored after callback

Timer Execution

Run All Timers

Executes all pending timers, immediates, and ticks until none remain.

/**
 * Runs all pending timers until none remain
 */
runAllTimers(): void;

Usage Example:

setTimeout(() => console.log('Timer 1'), 100);
setTimeout(() => console.log('Timer 2'), 200);

fakeTimers.runAllTimers();
// Both timers execute in order

Run Only Pending Timers

Executes only the timers that are currently pending, preserving execution order.

/**
 * Runs only currently pending timers
 */
runOnlyPendingTimers(): void;

Run All Ticks

Executes all pending process.nextTick callbacks.

/**
 * Runs all pending process.nextTick callbacks
 */
runAllTicks(): void;

Run All Immediates

Executes all pending setImmediate callbacks.

/**
 * Runs all pending setImmediate callbacks
 */
runAllImmediates(): void;

Time Advancement

Advance Timers by Time

Advances the fake clock by the specified number of milliseconds.

/**
 * Advances fake time by specified milliseconds
 * @param msToRun - Number of milliseconds to advance
 */
advanceTimersByTime(msToRun: number): void;

Usage Example:

let executed = false;
setTimeout(() => { executed = true; }, 1000);

fakeTimers.advanceTimersByTime(1000);
console.log(executed); // true

Advance Timers to Next Timer

Advances time to the next scheduled timer and optionally repeats.

/**
 * Advances time to the next scheduled timer
 * @param steps - Number of timer steps to advance (default: 1)
 */
advanceTimersToNextTimer(steps?: number): void;

Usage Example:

setTimeout(() => console.log('First'), 100);
setTimeout(() => console.log('Second'), 200);

fakeTimers.advanceTimersToNextTimer(1);
// Executes 'First', time is now at 100ms

fakeTimers.advanceTimersToNextTimer(1);
// Executes 'Second', time is now at 200ms

State Management

Reset

Resets all timer state to initial conditions.

/**
 * Resets all timer state to initial conditions
 */
reset(): void;

Clear All Timers

Clears all pending timers without executing them.

/**
 * Clears all pending timers
 */
clearAllTimers(): void;

Now

Returns the current fake time.

/**
 * Gets current fake time in milliseconds
 * @returns Current fake time
 */
now(): number;

Get Timer Count

Returns the total number of pending timers, immediates, and ticks.

/**
 * Gets the total count of pending timers
 * @returns Number of pending timers, immediates, and ticks
 */
getTimerCount(): number;

Dispose

Disposes of the fake timers instance and clears all state.

/**
 * Disposes of the fake timers instance
 */
dispose(): void;

Types

type Callback = (...args: Array<unknown>) => void;

interface TimerConfig<Ref> {
  /** Convert timer ID to reference */
  idToRef: (id: number) => Ref;
  /** Convert reference to timer ID */
  refToId: (ref: Ref) => number | void;
}

interface ModuleMocker {
  fn<T extends FunctionLike = UnknownFunction>(
    implementation?: T
  ): Mock<T>;
}

interface StackTraceConfig {
  rootDir: string;
  testMatch: Array<string>;
}

Error Handling

Legacy fake timers include protection against infinite recursion:

  • Maximum Loop Protection: Prevents infinite timer loops with configurable maxLoops parameter (default: 100,000)
  • Stack Trace Integration: Provides detailed error messages with stack traces when timer limits are exceeded
  • Proper Cleanup: Ensures timers are properly disposed of to prevent memory leaks

docs

index.md

legacy-fake-timers.md

modern-fake-timers.md

tile.json