Jest Mock Date Not Working Fix
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()inbeforeEachfor 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
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - 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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro