Skip to content

Jest Mock Date Not Working Fix

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about Jest Mock Date Not Working Fix. We cover key concepts, practical examples, and best practices.

Your test that depends on the current date fails randomly — sometimes it passes, sometimes it doesn't. The test behaves differently based on when it runs.

The Problem

// WRONG — depends on real Date
test('generates date-based ID', () => {
  const id = `order-${Date.now()}`;
  expect(id).toMatch(/^order-\d+$/);
  // Passes, but the actual value is unpredictable
});

// WRONG — Date.now varies every millisecond
test('calculates age from birthdate', () => {
  const birthDate = new Date('2000-01-01');
  const age = new Date().getFullYear() - birthDate.getFullYear();
  // Age changes every year!
  expect(age).toBe(24); // Fails in 2025+
});

The test passes today but fails tomorrow. Time-dependent tests are inherently non-deterministic.

Step-by-Step Fix

1. Mock Date.now

// RIGHT — deterministic Date.now
beforeEach(() => {
  jest.spyOn(Date, 'now').mockReturnValue(1700000000000);
});

afterEach(() => {
  jest.restoreAllMocks();
});

test('generates date-based ID', () => {
  const id = `order-${Date.now()}`;
  expect(id).toBe('order-1700000000000');
});

2. Mock the Date constructor

// RIGHT — fixed current date
beforeAll(() => {
  jest.useFakeTimers();
  jest.setSystemTime(new Date('2024-06-15'));
});

afterAll(() => {
  jest.useRealTimers();
});

test('calculates age', () => {
  const birthDate = new Date('2000-01-01');
  const age = new Date().getFullYear() - birthDate.getFullYear();
  expect(age).toBe(24);
});

3. Use date-fns or dayjs mocks

// RIGHT — mock date utility library
jest.mock('date-fns', () => ({
  format: jest.fn(() => '2024-06-15'),
  parseISO: jest.fn(() => new Date('2024-06-15')),
}));

4. Snapshot with property matchers

// RIGHT — matchers for dynamic date fields
test('creates user with timestamp', () => {
  const user = createUser('Alice');
  expect(user).toMatchSnapshot({
    createdAt: expect.any(Date),
    updatedAt: expect.any(Date),
  });
});

Expected output:

PASS  tests/date.test.js
  ✓ generates date-based ID (4 ms)
  ✓ calculates age (3 ms)
  ✓ creates user with timestamp (6 ms)

Prevention Tips

  • Mock Date.now() in beforeEach for deterministic tests
  • Use jest.setSystemTime() for full Date control
  • Always restore mocks in afterEach
  • Use property matchers in snapshots for date fields
  • Test timezone-sensitive code with a fixed timezone

Common Mistakes with mock date

  1. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  2. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  3. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks

These mistakes appear frequently in real-world JEST code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Does jest.setSystemTime affect Date objects or just Date.now?

Both. jest.setSystemTime() affects new Date(), Date.now(), and new Date().getTime(). It provides a complete frozen time environment for your tests.

How do I test timezone-specific date behavior?

Use process.env.TZ = 'UTC' in beforeAll and restore it in afterAll. Combined with jest.setSystemTime(), this gives you full control over both time and timezone in your tests.

Can I use fake timers and mock Date at the same time?

Yes. jest.useFakeTimers() includes date mocking via jest.setSystemTime(). Call jest.setSystemTime() after jest.useFakeTimers() to set both fake timers and a fixed date simultaneously.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro