Vehicles Time Travel Utility

10.0.23 · active · verified Sun Apr 19

Vehicles is a JavaScript/TypeScript testing utility designed to manipulate the system's time, enabling developers to 'travel into the future' for deterministic testing of time-sensitive code. It achieves this by mocking and controlling internal timers, such as `setTimeout`, `setInterval`, and `Date.now()`, allowing tests to execute scenarios involving time progression without actual real-time waits. The current stable version is 10.0.23, with a release cadence that appears to be frequent, primarily consisting of patch releases. Its key differentiator lies in providing a controlled environment for asynchronous operations and date-based logic, ensuring test reliability and speed. The package explicitly targets Node.js environments, requiring version 18.2.0 or higher.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use `vehicles` to mock and advance timers for testing asynchronous, time-dependent logic and validating mocked date objects.

import { travel, reset } from 'vehicles';

describe('Time-sensitive feature', () => {
  // Store original Date to restore after all tests
  const originalDate = global.Date;

  beforeEach(() => {
    // Reset time mocks before each test to ensure isolation
    reset();
  });

  afterAll(() => {
    // Restore global Date object after all tests in the suite
    global.Date = originalDate;
  });

  it('should trigger an event after a specific delay', async () => {
    let eventTriggered = false;
    setTimeout(() => {
      eventTriggered = true;
    }, 10000); // 10 seconds

    // Initial state check
    expect(eventTriggered).toBe(false);

    // Travel 5 seconds into the future
    await travel(5000);
    expect(eventTriggered).toBe(false); // Should still be false

    // Travel another 5 seconds (total 10) to trigger the event
    await travel(5000);
    expect(eventTriggered).toBe(true);
  });

  it('should mock current date correctly', async () => {
    const initialDate = new Date();
    await travel(60 * 60 * 1000); // Travel 1 hour into the future
    const afterTravelDate = new Date();
    expect(afterTravelDate.getTime()).toBe(initialDate.getTime() + 60 * 60 * 1000);
  });
});

view raw JSON →