Testing and QA · Intermediate · 25 min
Test time-dependent code with fake clocks
By Padding · Updated 18 Nov 2026
Node.js 26 · Vitest 5.1.1 · Python 3 · pytest 9.2.0 · time-machine 3.6.0 · checked on node:26
You will test expiry, month ends, retries and daylight saving changes in Python and JavaScript with a fake clock, so tests that read the time pass on any day and in any time zone.
On this page
Code that reads the clock hides bugs that only show up on certain days. A renewal date that crashes on 31 January, a voucher that expires an hour early after the clocks change, a retry loop that makes a test suite sit idle for seconds: none of these appear when you run the tests at 2 pm on a Tuesday. They appear at midnight, at the end of the month, or on the last Sunday of October, usually in production.
The fix is to take control of time in your tests. In order of preference:
- Pass the clock in. The code asks a function or argument for "now", and the test hands it a fixed time it can move forward.
- Freeze or move the clock from outside when you cannot change the code. In Python that is time-machine; in Vitest it is
vi.useFakeTimers()withvi.setSystemTime(). - Advance fake timers for code that waits, such as retries with back-off, so a test of a seven-second retry finishes in milliseconds.
You build a small demo with a Python half and a JavaScript half. The examples are payments and prepaid data: bundle expiry, monthly renewals, one-time codes and SMS quiet hours. Two time zones run through the whole tutorial: Africa/Lagos, which stays on UTC+1 all year, and Europe/London, which moves between UTC+0 and UTC+1. A team whose developers and test machines all sit in Lagos never sees a daylight saving bug on their own machines, yet a user sending money home from London can still hit one.
Step 1 · Set up the Python project
Make a throwaway folder with a virtual environment, and pin pytest and time-machine. The commands call the environment's Python directly, so you do not need to activate it.
mkdir -p ~/fake-clocks-demo/python/tests
cd ~/fake-clocks-demo/python
python3 -m venv .venv
.venv/bin/python -m pip install --quiet pytest==9.2.0 time-machine==3.6.0
cat > pytest.ini <<'INI'
[pytest]
testpaths = tests
pythonpath = .
INI
.venv/bin/python -m pytest --version
.venv/bin/python -m pip show time-machine | grep '^Version'time-machine registers itself as a pytest plugin when it is installed. It gives you a time_machine fixture and a time_machine marker; you use both in a later step.
Check it worked
The last two commands print pytest 9.2.0 and Version: 3.6.0.
Step 2 · Find a month-end bug by passing the date in
Here is a monthly data plan that renews on the same day next month. It reads today's date when the caller does not pass one:
cd ~/fake-clocks-demo/python
cat > renewals.py <<'PY'
from datetime import date
def next_renewal(today=None):
"""The plan renews on the same day of the following month."""
today = today or date.today()
return today.replace(month=today.month + 1)
PYA test that calls next_renewal() with no argument checks whatever today happens to be. On most days of the year it passes. Because the function accepts a date, the test can pick the days that matter instead: an ordinary day, the 31st of a month followed by a shorter one, December, and a leap year.
cd ~/fake-clocks-demo/python
cat > tests/test_renewals.py <<'PY'
from datetime import date
import pytest
from renewals import next_renewal
@pytest.mark.parametrize(
"today, expected",
[
(date(2026, 3, 10), date(2026, 4, 10)), # an ordinary day
(date(2026, 1, 31), date(2026, 2, 28)), # no 31 February
(date(2026, 12, 15), date(2027, 1, 15)), # into a new year
(date(2028, 1, 31), date(2028, 2, 29)), # leap year
],
)
def test_next_renewal(today, expected):
assert next_renewal(today) == expected
PY
.venv/bin/python -m pytest -q tests/test_renewals.py || echo "renewal tests failed"Three cases fail with ValueError: day is out of range for month for 31 January and the leap year, and month must be in 1..12 for December. Fix the function so it clamps to the last day of the target month and rolls the year over:
cd ~/fake-clocks-demo/python
cat > renewals.py <<'PY'
import calendar
from datetime import date
def next_renewal(today=None):
"""The plan renews on the same day of the following month,
or on that month's last day if it is shorter."""
today = today or date.today()
if today.month == 12:
year, month = today.year + 1, 1
else:
year, month = today.year, today.month + 1
last_day = calendar.monthrange(year, month)[1]
return date(year, month, min(today.day, last_day))
PY
.venv/bin/python -m pytest -q tests/test_renewals.pyClamping is a business rule, not only a bug fix: a plan bought on 31 January now renews on 28 February and then on 28 March, not 31 March. Agree the rule with whoever owns the product and write it into a test, as here.
Check it worked
The first run prints 3 failed, 1 passed. After the fix it prints 4 passed.
Step 3 · Give expiring objects a clock you can move
A date argument is enough for pure functions. Objects that check the time again later, such as a data bundle asked "are you still active?", need a clock they can call each time. Pass in a function that returns the current time, and use the real one by default:
cd ~/fake-clocks-demo/python
cat > bundles.py <<'PY'
from datetime import datetime, timezone
def system_clock():
return datetime.now(timezone.utc)
class Bundle:
def __init__(self, megabytes, validity, clock=system_clock):
self.megabytes = megabytes
self._clock = clock
self.expires_at = clock() + validity
def is_active(self):
return self._clock() < self.expires_at
PYIn the tests, a small fake clock returns a fixed time and moves only when you tell it to. Put it in conftest.py so every test file can ask for it:
cd ~/fake-clocks-demo/python
cat > tests/conftest.py <<'PY'
from datetime import datetime, timedelta, timezone
import pytest
class FakeClock:
def __init__(self, start):
self.now = start
def __call__(self):
return self.now
def advance(self, **delta):
self.now += timedelta(**delta)
@pytest.fixture
def clock():
# 23:30 UTC on the last day of January: midnight and a month end are close.
return FakeClock(datetime(2026, 1, 31, 23, 30, tzinfo=timezone.utc))
PY
cat > tests/test_bundles.py <<'PY'
from datetime import timedelta
from bundles import Bundle
def test_active_one_second_before_expiry(clock):
bundle = Bundle(1024, timedelta(days=1), clock=clock)
clock.advance(days=1, seconds=-1)
assert bundle.is_active()
def test_expired_at_exactly_its_validity(clock):
bundle = Bundle(1024, timedelta(days=1), clock=clock)
clock.advance(days=1)
assert not bundle.is_active()
def test_night_bundle_lasts_past_midnight(clock):
bundle = Bundle(500, timedelta(hours=1), clock=clock)
clock.advance(minutes=45) # 00:15 on 1 February
assert bundle.is_active()
PY
.venv/bin/python -m pytest -q tests/test_bundles.pyThe second test pins down a decision customers notice: at the exact expiry instant the bundle is gone. If your product promises "valid until 23:59 on the last day", the rule is different, and the test is where you record it. Testing one second either side of the boundary catches the < versus <= mistakes that a test bought "now" and checked "now" never will.
Check it worked
The run prints 3 passed. Change < to <= in is_active and run it again: test_expired_at_exactly_its_validity fails. Change it back.
Step 4 · Freeze time in code you cannot change with time-machine
Sometimes the clock read is buried in code you cannot refactor today: a legacy module, or a library. Here a shop module names its daily report after today's date and decides opening hours from the server's local time:
cd ~/fake-clocks-demo/python
cat > shop.py <<'PY'
import datetime as dt
def report_filename():
return f"sales-{dt.date.today().isoformat()}.csv"
def is_open_now():
"""Open 08:00 to 20:00. The server runs in the shop's time zone."""
return 8 <= dt.datetime.now().hour < 20
PYtime-machine replaces the standard library's clock functions (datetime.now(), date.today(), time.time() and others) at the C level, so every caller sees the mocked time, wherever it imported them from. If the destination datetime has a ZoneInfo time zone, time-machine also sets the process's local time zone to match, which is what is_open_now depends on.
cd ~/fake-clocks-demo/python
cat > tests/test_shop.py <<'PY'
import datetime as dt
from zoneinfo import ZoneInfo
import pytest
import shop
LAGOS = ZoneInfo("Africa/Lagos")
@pytest.mark.time_machine(dt.datetime(2026, 6, 1, 12, 0, tzinfo=LAGOS), tick=False)
def test_report_named_after_today():
assert shop.report_filename() == "sales-2026-06-01.csv"
def test_report_name_changes_at_midnight(time_machine):
time_machine.move_to(dt.datetime(2026, 1, 31, 23, 59, 30, tzinfo=LAGOS), tick=False)
assert shop.report_filename() == "sales-2026-01-31.csv"
time_machine.shift(dt.timedelta(seconds=60))
assert shop.report_filename() == "sales-2026-02-01.csv"
@pytest.mark.parametrize("hour, expected", [(7, False), (8, True), (19, True), (20, False)])
def test_opening_hours(time_machine, hour, expected):
time_machine.move_to(dt.datetime(2026, 6, 1, hour, 0, tzinfo=LAGOS), tick=False)
assert shop.is_open_now() is expected
PY
.venv/bin/python -m pytest -q tests/test_shop.py
TZ=Asia/Tokyo .venv/bin/python -m pytest -q tests/test_shop.pyThe marker sets the time for one whole test. The fixture lets a test move the clock part-way through, with move_to() to jump and shift() to step forward. tick=False freezes the clock, so two calls a microsecond apart return the same time; leave it at the default True when the code measures how long something took.
Know the limits before you rely on it:
time.monotonic()andtime.perf_counter()are not mocked, so a timeout loop built on them still waits in real time.- Only this Python process travels. A database's
NOW(), SQLite'sdatetime('now')and any subprocess still see the real clock; pass the time in as a parameter instead. - Time is global, so other threads see the mocked time too.
time-machine is a bridge, not a goal. Once the test pins the behaviour down, refactoring the module to accept a clock is safer, and the test tells you if you broke it.
Check it worked
Both runs print 6 passed. The second run sets the machine's time zone to Tokyo, eight hours ahead of Lagos, and the opening-hours tests still pass because time-machine sets the zone from the destination.
Step 5 · Test a daily reminder across a daylight saving change
A savings app reminds each user at 09:00 in their own time zone. This first version stores the reminder in UTC and adds 24 hours to get the next one:
cd ~/fake-clocks-demo/python
cat > reminders.py <<'PY'
from datetime import timedelta
def following_reminder(previous_utc, tz_name):
"""The reminder after previous_utc, at the same local time the next day."""
return previous_utc + timedelta(hours=24)
PY
cat > tests/test_reminders.py <<'PY'
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
import pytest
from reminders import following_reminder
def utc(*parts):
return datetime(*parts, tzinfo=timezone.utc)
@pytest.mark.parametrize(
"tz_name, previous, expected",
[
# Lagos is UTC+1 all year: 09:00 local is always 08:00 UTC.
("Africa/Lagos", utc(2026, 3, 28, 8, 0), utc(2026, 3, 29, 8, 0)),
("Africa/Lagos", utc(2026, 10, 24, 8, 0), utc(2026, 10, 25, 8, 0)),
# London: clocks go forward on 29 March and back on 25 October 2026.
("Europe/London", utc(2026, 3, 28, 9, 0), utc(2026, 3, 29, 8, 0)),
("Europe/London", utc(2026, 10, 24, 8, 0), utc(2026, 10, 25, 9, 0)),
],
)
def test_reminder_stays_at_nine_local(tz_name, previous, expected):
following = following_reminder(previous, tz_name)
assert following == expected
assert following.astimezone(ZoneInfo(tz_name)).hour == 9
PY
.venv/bin/python -m pytest -q tests/test_reminders.py || echo "reminder tests failed"Both Lagos cases pass and both London cases fail: the reminder lands at 10:00 after the clocks go forward and at 08:00 after they go back. No test that uses today's date would catch this, because it only fails on two nights a year.
The rule is about local time, so do the arithmetic in local time. Convert to the user's zone, move to the same wall-clock time on the next day, and convert back:
cd ~/fake-clocks-demo/python
cat > reminders.py <<'PY'
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
def following_reminder(previous_utc, tz_name):
"""The reminder after previous_utc, at the same local time the next day."""
zone = ZoneInfo(tz_name)
local = previous_utc.astimezone(zone)
next_day = local.date() + timedelta(days=1)
return datetime.combine(next_day, local.time(), tzinfo=zone).astimezone(timezone.utc)
PY
.venv/bin/python -m pytest -q tests/test_reminders.py
.venv/bin/python -m pytest -qIf a reminder time could fall inside the hour that does not exist (01:30 in London on 29 March), decide what should happen and add a case for it. Times near 01:00 to 02:00 are where daylight saving bugs live; 09:00 is safe.
Check it worked
The first run prints 2 failed, 2 passed. After the fix, tests/test_reminders.py prints 4 passed and the whole suite prints 17 passed.
Step 6 · Set up Vitest and test a code that expires
The JavaScript half lives in its own folder. Pin Vitest and make the project use ES modules:
mkdir -p ~/fake-clocks-demo/js/test
cd ~/fake-clocks-demo/js
npm init -y > /dev/null
npm pkg set type=module
npm install --save-dev --save-exact vitest@5.1.1
npx vitest --versionA one-time code for confirming a mobile money transfer is valid for five minutes. The code reads Date.now() directly, which is common in JavaScript:
cd ~/fake-clocks-demo/js
cat > otp.js <<'JS'
export const CODE_LIFETIME_MS = 5 * 60 * 1000;
export function issueCode(code) {
return { code, expiresAt: Date.now() + CODE_LIFETIME_MS };
}
export function checkCode(issued, entered) {
if (Date.now() >= issued.expiresAt) return 'expired';
return entered === issued.code ? 'ok' : 'wrong';
}
JS
cat > test/otp.test.js <<'JS'
import { afterEach, beforeEach, expect, test, vi } from 'vitest';
import { checkCode, issueCode } from '../otp.js';
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-03-31T23:58:00Z'));
});
afterEach(() => {
vi.useRealTimers();
});
test('accepts the code one second before it expires', () => {
const issued = issueCode('482913');
vi.advanceTimersByTime(5 * 60 * 1000 - 1000);
expect(checkCode(issued, '482913')).toBe('ok');
});
test('rejects the code at exactly five minutes', () => {
const issued = issueCode('482913');
vi.advanceTimersByTime(5 * 60 * 1000);
expect(checkCode(issued, '482913')).toBe('expired');
});
test('an expired code stays expired across midnight and the month end', () => {
const issued = issueCode('482913');
vi.setSystemTime(new Date('2026-04-01T00:03:00Z'));
expect(checkCode(issued, '482913')).toBe('expired');
});
JS
npx vitest runvi.useFakeTimers() swaps in a fake clock for Date, setTimeout, setInterval and friends. vi.setSystemTime() jumps the clock to a given moment without running any timers, like someone changing the time on their phone. vi.advanceTimersByTime() moves the clock forward and runs every timer due on the way. Always switch back with vi.useRealTimers() in afterEach, or the fake clock leaks into the next test file that runs in the same worker.
Check it worked
The first command prints a version line containing 5.1.1. The run lists test/otp.test.js and ends with 3 passed.
Step 7 · Test retries without waiting for them
Payment providers time out, especially on patchy mobile connections, so a client retries. This one waits 1, 2 and then 4 seconds between attempts:
cd ~/fake-clocks-demo/js
cat > retry.js <<'JS'
export async function withRetry(task, delaysMs = [1000, 2000, 4000]) {
for (let attempt = 0; ; attempt += 1) {
try {
return await task();
} catch (error) {
if (attempt >= delaysMs.length) throw error;
await new Promise((resolve) => setTimeout(resolve, delaysMs[attempt]));
}
}
}
JS
cat > test/retry.test.js <<'JS'
import { afterEach, beforeEach, expect, test, vi } from 'vitest';
import { withRetry } from '../retry.js';
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
test('waits one second, then two, between attempts', async () => {
const task = vi
.fn()
.mockRejectedValueOnce(new Error('timeout'))
.mockRejectedValueOnce(new Error('timeout'))
.mockResolvedValue('paid');
const result = withRetry(task);
await vi.advanceTimersByTimeAsync(0);
expect(task).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(999);
expect(task).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(1);
expect(task).toHaveBeenCalledTimes(2);
await vi.advanceTimersByTimeAsync(2000);
expect(task).toHaveBeenCalledTimes(3);
await expect(result).resolves.toBe('paid');
});
test('gives up after the last delay and reports the error', async () => {
const task = vi.fn().mockRejectedValue(new Error('timeout'));
const outcome = expect(withRetry(task)).rejects.toThrow('timeout');
await vi.advanceTimersByTimeAsync(7000);
await outcome;
expect(task).toHaveBeenCalledTimes(4);
});
JS
npx vitest run test/retry.test.jsUse the Async version of the advance functions whenever the code awaits a promise between timers. It lets pending promise callbacks run before and after each timer, so the retry loop gets the chance to schedule its next wait. With the plain vi.advanceTimersByTime(), the retry's next setTimeout may not exist yet when the clock moves, so the test can see fewer calls than it expects.
The 999 ms check matters as much as the 1000 ms one: it proves the client really waits, rather than hammering the provider. In the second test, the expect(...).rejects is attached before the clock moves, so the rejection is always handled.
Check it worked
The run prints 2 passed, and the Duration line in the summary is well under a second, not the seven seconds of delays the code asks for.
Step 8 · Test time zones the machine cannot change
An SMS service must not text people between 21:00 and 07:00 in their own time zone. The first version uses getHours(), which answers in the time zone of the machine running the code:
cd ~/fake-clocks-demo/js
cat > quiet.js <<'JS'
export function isQuietHours(timeZone) {
const hour = new Date().getHours(); // the machine's zone, not the user's
return hour >= 21 || hour < 7;
}
JS
cat > test/quiet.test.js <<'JS'
import { afterEach, expect, test, vi } from 'vitest';
import { isQuietHours } from '../quiet.js';
afterEach(() => {
vi.useRealTimers();
});
test.each([
// 24 October 2026: London is on summer time (UTC+1), the same as Lagos.
['2026-10-24T06:30:00Z', 'Africa/Lagos', false],
['2026-10-24T06:30:00Z', 'Europe/London', false],
// 25 October 2026: London is back on UTC+0, so 06:30 UTC is 06:30 there.
['2026-10-25T06:30:00Z', 'Africa/Lagos', false],
['2026-10-25T06:30:00Z', 'Europe/London', true],
// A December evening: 21:30 in Lagos, 20:30 in London.
['2026-12-01T20:30:00Z', 'Africa/Lagos', true],
['2026-12-01T20:30:00Z', 'Europe/London', false],
])('at %s, quiet hours in %s is %s', (instant, timeZone, expected) => {
vi.useFakeTimers();
vi.setSystemTime(new Date(instant));
expect(isQuietHours(timeZone)).toBe(expected);
});
JS
TZ=Africa/Lagos npx vitest run test/quiet.test.js || echo "quiet hours tests failed"Run on a machine set to Lagos, every Lagos case passes and two London cases fail. A developer in Lagos sees a mostly green suite, and a CI runner set to UTC fails a different set of cases. Setting the system time does not help on its own: vi.setSystemTime() moves the clock, not the time zone. The code has to ask for the user's zone:
cd ~/fake-clocks-demo/js
cat > quiet.js <<'JS'
function localHour(timeZone, now) {
const parts = new Intl.DateTimeFormat('en-GB', {
timeZone,
hour: 'numeric',
hourCycle: 'h23',
}).formatToParts(now);
return Number(parts.find((part) => part.type === 'hour').value);
}
export function isQuietHours(timeZone) {
const hour = localHour(timeZone, new Date());
return hour >= 21 || hour < 7;
}
JS
for zone in Africa/Lagos UTC Asia/Tokyo; do
TZ=$zone npx vitest run test/quiet.test.js
done
npx vitest runUse time zone names such as Africa/Lagos, not fixed offsets such as +01:00. A name carries the zone's daylight saving rules and any future changes to them; an offset is only right until the rules change. Store the user's zone name with their profile, and treat the phone's reported zone as a default the user can correct.
Check it worked
The first run prints 2 failed and 4 passed. After the fix, the three runs under different machine time zones each print 6 passed, and the full run prints 11 passed across three test files.
rm -rf ~/fake-clocks-demoWhen you have finished, rm -rf ~/fake-clocks-demo removes everything this tutorial created, including both virtual environment and node_modules folders.
Next steps
- Refresh fixtures and parametrize, used throughout this tutorial: test Python code with pytest.
Related tutorials
- Triage bugs by severity and priorityYou will have a one-page triage guide for your team, with severity and priority scales, named decision owners, rules for duplicates and won't-fix, a response time per priority and three metrics to review each week.
- Test email sending with Mailpit as a local SMTP catcherYou will point a small Python app's SMTP settings at Mailpit 1.34 so no real email leaves your machine, then use pytest and Mailpit's API to check the subject, recipients, links, text and HTML parts and HTML client support of every message it sends.
- Speed up a slow pytest suiteYou will take a sample pytest suite from about 18 seconds to about 2 by measuring it, widening a fixture scope, removing fixed sleeps, stubbing a slow external call, running it in parallel with pytest-xdist and splitting it across CI shards.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials