patternModeratepending
Mocking time in tests — deterministic date and timer testing
Viewed 0 times
fake timersuseFakeTimerssetSystemTimefreezegunadvanceTimersByTimedeterministic
nodejsbrowser
Problem
Tests that depend on dates, timestamps, or timers are flaky. Tests pass at certain times of day but fail at others. setTimeout/setInterval tests are slow because they wait for real time.
Solution
Mock the clock. Jest: jest.useFakeTimers(); jest.advanceTimersByTime(1000); jest.useRealTimers(). Vitest: vi.useFakeTimers(); vi.advanceTimersByTime(1000). For dates: jest.setSystemTime(new Date('2024-01-15')). Python: from unittest.mock import patch; @patch('module.datetime') or use freezegun: @freeze_time('2024-01-15'). Key: (1) Mock time at the start of the test. (2) Advance time explicitly. (3) Restore real timers in afterEach. (4) Be careful with Promise resolution — you may need to advance timers AND flush microtasks.
Why
Real time makes tests non-deterministic. A test checking 'created today' fails tomorrow. Timer tests that wait 5 real seconds make the suite slow. Fake timers give you full control.
Revisions (0)
No revisions yet.