Course contentsShow
← React
Lesson 2130 of 2,39647. Testing Patterns and Best PracticesFree lesson

Mocking Date and Time Utilities

Control time-dependent behavior with libraries like vitest's vi.useFakeTimers() for predictable tests.

Mocking Date and Time Utilities

What You'll Learn

You'll learn how to control time-dependent behavior in tests using Vitest's fake timers to make tests predictable and reliable.

The Problem with Real Time

When your components depend on Date.now(), setTimeout, or setInterval, tests become unpredictable. A component that renders "5 seconds ago" will give different results depending on when the test runs. Time keeps moving, but tests should be deterministic.

Controlling Time with Fake Timers

Vitest provides vi.useFakeTimers() to freeze time and control its passage manually. Think of it like pausing a movie—you can start, stop, and fast-forward at will:

import { vi, describe, it, beforeEach, afterEach, expect } from 'vitest';
import { render, screen } from '@testing-library/react';

function TimeSensitiveComponent() {
  const [time] = useState(() => new Date().toISOString());
  return <div>{time}</div>;
}

describe('TimeSensitiveComponent', () => {
  beforeEach(() => {
    vi.useFakeTimers();
    vi.setSystemTime(new Date('2024-01-15T10:00:00Z'));
  });

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

  it('renders fixed timestamp', () => {
    render(<TimeSensitiveComponent />);
    expect(screen.getByText(/2024-01-15T10:00:00/)).toBeInTheDocument();
  });

  it('advances time with advanceTimersByTime', () => {
    // Test components with setTimeout/setInterval
    vi.advanceTimersByTime(5000); // Jump forward 5 seconds
  });
});

Why This Matters

Without fake timers, you'd write flaky tests that depend on system time or arbitrary await delays. With them, you control exactly when time passes, making tests fast, reliable, and repeatable.

Key Takeaway: Use vi.useFakeTimers() and vi.setSystemTime() to freeze and control time in tests, ensuring predictable behavior for components that depend on dates, timers, or intervals—always restore real timers afterward with vi.useRealTimers().