X · Testing
Time
On this page
Introduction
Tests often need time to pass: a rate limit to reset, a link to expire, a nightly task to come due. Every test app has a test
clock as the app's Clock, and the test moves it instead of waiting:
import { createTestApp } from '@marmeon/testing';
import { it } from 'vitest';
import application from '../../bootstrap/app.ts';
import { UserFactory } from './factories/UserFactory.ts';
it('lets a user try again a minute after five failed sign-ins', async () => {
const app = await createTestApp(application, { database: 'refresh' });
const ada = await app.factory(UserFactory).create();
const signIn = (password: string) => app.post('/login', { form: { email: ada.email, password } });
app.freeze();
for (let attempt = 0; attempt < 5; attempt++) await signIn('wrong');
await signIn('password').assertInvalid({ email: /^Too many login attempts/ }).assertGuest();
app.travel({ seconds: 61 });
await signIn('password').assertRedirect('/dashboard').assertAuthenticated(ada);
});No timer is faked and nothing sleeps. The rate limiter reads the time through the app's clock, so it sees the minute pass.
Moving the clock
| Method | What it does |
|---|---|
app.freeze(time) | Stops the clock, at time when given, else now. Returns the frozen time in milliseconds. |
app.travel(duration) | Moves the clock by a duration: seconds as a number (app.travel(90)), or an object such as { minutes: 61 }. Negative values move it back. |
app.travelTo(time) | Jumps to a Date or epoch milliseconds. |
app.clock.unfreeze() | Lets the clock run again from where it stands. |
app.clock.now() | The app's time in milliseconds, as the app's services read it. |
A clock that is not frozen runs with the real time, plus the distance you travelled. A frozen clock stands still until the next
travel() or travelTo(), which moves it and leaves it frozen. Freeze it when a test compares exact times:
import { createTestApp } from '@marmeon/testing';
import { expect, it } from 'vitest';
import application from '../../bootstrap/app.ts';
it('moves a frozen clock by exactly the duration', async () => {
const app = await createTestApp(application);
const start = app.freeze(Date.parse('2026-10-04T12:00:00Z'));
app.travel({ hours: 1, seconds: 30 });
expect(app.clock.now()).toBe(start + 3_630_000);
});A number means seconds (app.travel(90)); an object takes days, hours, minutes, seconds and milliseconds. Each test app has its own clock, so one test's travel
never reaches another test.
Spans of time
Duration from @marmeon/core is the one type for a span of time. It is a number of seconds, or an object with the parts
days, hours, minutes, seconds and milliseconds: 90, { minutes: 5 }, { hours: 1, seconds: 30 }. A Temporal.Duration
fits too. There are no strings: '60m' is a TypeError that names the object to write, { minutes: 60 }, so a typo never turns into
a link without an expiry. The parts years, months and weeks are refused as well, because their length depends on the calendar, and so are microseconds and nanoseconds, which a millisecond clock cannot keep.
durationToSeconds(duration) and durationToMilliseconds(duration) turn one into a number, and refuse anything else.
Five rules say where a span is a Duration:
- An option or a parameter that takes a span and has no unit in its name is a
Duration:delay,release(),expiresIn,uniqueFor,once(fn, { for }), the HSTSmaxAge, themaxAgeoftwoFactor()andconfirmedPassword(), thettlof the cache,lock()andblock()of a lock, the window of aLimit, andRoute.block(). - A number with a unit in its name stays a number:
keepAliveTimeoutMs,SESSION_MAX_SECONDS, a measureddurationMs. - A name without a unit never holds a bare number that means something else than seconds. A
Durationis seconds when it is a number. - A contract that your app implements, such as a cache store or a lock store, gets normalised numbers with the unit in the name,
never a
Duration. - What the framework returns or lays out for you to read, such as a return value, a field of a resolved config, the context of a
middleware or a field of an event, is a normalised number with the unit in its name:
retryAfterSeconds,sessionMaxSeconds,resetMinutes,lifetimeMinutes. ADurationis an input only.
A span in a position of a parameter is a Duration, or it moves into an options object; the unit in a parameter name would never
show at the call.
An expiry is rounded down to a whole second, so a link or a token never lives longer than you asked: { seconds: 1, milliseconds: 900 }
expires after one second. A Limit takes only whole seconds, because its window is part of the key its count is stored under.
A time typed in a zone
A datetime-local field sends 2026-10-07T14:30: a date and a time with no zone. The zone is the event's, so the form sends it too, and
r.localDateTime() turns the pair into an instant:
import { defineRequest } from '@marmeon/http';
import { rules as r } from '@marmeon/validation';
export const StoreEventRequest = defineRequest({
schema: r
.object({
title: r.string().trim().required().max(120),
time_zone: r.timeZone(), // a name only, in IANA's spelling: `europe/berlin` becomes `Europe/Berlin`
starts_at: r.localDateTime({ field: 'time_zone' }),
ends_at: r.localDateTime({ field: 'time_zone' }),
})
.custom((event) => event.ends_at > event.starts_at, { message: 'The end comes before the start.', field: 'ends_at' }),
});starts_at in the handler is '2026-10-07T12:30:00.000Z' for 2026-10-07T14:30 in Europe/Berlin: store it as a timestamp column. The
check in custom() runs after the conversion, so it compares instants, and it is a plain string comparison because every instant has the same shape. A zone that is a fixed name for the whole form
can be written in the rule: r.localDateTime('Europe/Berlin').
Store the zone of a place, not an offset: an offset knows no summer time, so an event saved with +01:00 shows the wrong hour half of the year. That is why r.timeZone() takes only names.
Two nights a year the wall clock has no single answer, and the rule picks one, the same way every time:
- When the clocks go forward, a time inside the skipped hour does not exist.
02:30on the night of 2026-03-29 inEurope/Berlinis read with the offset from before the change and becomes03:30(summer time),2026-03-29T01:30:00.000Z. - When the clocks go back, a time in the repeated hour happens twice.
02:30on 2026-10-25 inEurope/Berlinis the first one, in summer time:2026-10-25T00:30:00.000Z. The second02:30cannot be typed into a field that shows no offset.
To edit the event, fill the field with toLocalDateTime(instant, zone) from @marmeon/validation. It gives 2026-10-07T14:30, with seconds
when the instant has some, and it throws a RangeError for a zone or a point in time it does not know:
import { toLocalDateTime } from '@marmeon/validation';
const form = { time_zone: event.time_zone, starts_at: toLocalDateTime(event.starts_at, event.time_zone) };A time in the skipped hour comes back as the 03:30 it was read as, so a saved event shows the time it really starts.
A calendar day
A date column is a day, not an instant: it reads back as 2026-10-14 and means the 14th in every zone. A date placeholder,
and format.date() without a timeZone, show such a value as that day wherever the server or the browser runs, so a page in Los
Angeles does not say the 13th:
format.date(event.starts_on, { dateStyle: 'long' }); // "October 14, 2026", in every zoneOnly a string of the form YYYY-MM-DD is read this way. An instant (2026-10-14T00:00:00Z, a Date, a timestamp) is still shown
in the zone of the process or the one in timeZone. An explicit timeZone takes precedence for a day too: 2026-10-14 with
timeZone: 'America/Los_Angeles' shows October 13. When you format a day with Intl yourself, say timeZone: 'UTC', and do
the same for a range:
const days = new Intl.DateTimeFormat(locale, { dateStyle: 'long', timeZone: 'UTC' });
days.formatRange(new Date(event.starts_on), new Date(event.ends_on)); // "October 14 – 16, 2026"Showing a stored instant in a zone
An instant has no zone of its own, so a page that prints one picks the zone. Three places can name it, and the first that does wins:
- the call:
timeZoneofformat.date(), for example thetime_zoneof the record, as in A time typed in a zone; - the app:
APP_TIMEZONE, see The app's zone; - the process: the zone of the server, and of the visitor's browser.
A calendar day sits above the app's zone: it is the same day everywhere, see A calendar day. Hand the record's zone to the formatter, so the server and the browser render the same text:
<time dateTime={event.starts_at}>
{t.format.date(event.starts_at, { dateStyle: 'medium', timeStyle: 'short', timeZone: event.time_zone })}
</time>Without a zone from the call or the app, the formatter uses the zone of the process, which differs between the server and a visitor's browser and shows as a hydration mismatch.
The app's zone
An app whose times belong to one place sets the zone once:
APP_TIMEZONE=Europe/Berlinformat.date(), t.format in a view and the date and time placeholders of a message then show an instant in Berlin, on the server
and in the browser alike: the server sends the zone with each page, and the browser formats with it. A mail or a job asks
Translators.for(locale) and gets the same zone. The value must name an IANA time zone, or the app does not start. Without it, an instant
is shown in the zone of the process, and an app that shows times in the visitor's own zone sets nothing.
APP_TIMEZONE only decides how an instant is shown. It is not SCHEDULE_TIMEZONE, which places tasks; setting one moves nothing of
the other. A user's own zone stays an explicit timeZone, from user.time_zone.
What follows the clock
Everything that reads the time through the app's Clock follows the test clock:
- the cache's expiry, locks and rate limits on the
memory,fileanddatabasedrivers; - the session's lifetime and its expiry on the server;
- signed URLs and temporary links to files;
- the day in a table export's file name, as the UTC day;
- password reset tokens, remember-me tokens and API tokens;
- the sign-in: its absolute lifetime, the window of a password confirmation (
confirmedPassword()), the proof of a second factor (twoFactor(),confirmedSecondFactor()) and the cap of a remember-me cookie (AUTH_REMEMBER_DAYS), and how long a started second-factor step stays open; - the delays and backoffs of queued jobs, which
app.queue.work()runs once they are due; - the scheduler, through
app.schedule; - the cached answer of the readiness check;
created_atandupdated_atof a table withtimestamps(), which a repository'sinsert(),insertMany(),insertMissing(),update(),relation().create()andattach(), a factory andcredentialWriter()stamp, anddeleted_atof a soft delete (a raw query does not: see below);- the
now()a factory definition reads.
Your own services follow it when they take a Clock through the constructor instead of calling Date.now(). The
context page shows how.
What does not follow it
Some time is not the app's to move:
- Redis keeps its own clock. A cache entry, a lock or a rate limit on the
redisdriver expires when Redis says so, whatever the test clock reads. Tests that travel use thememorydriver, which.env.testsets. - The database has its own clock too. A column default such as
current_timestamp, ornow()in a query, is the database server's time: a row written by a rawinsertInto()withoutcreated_atgets it. Date.now()andnew Date()in your code read the real time. Inject aClockwhere a test must move the time.- Timers such as
setTimeout()wait in real time. A job's timeout and a lock's wait are real waits.
A job that waits
A job dispatched with a delay waits on the queue fake until the clock reaches it. work() runs only what is due:
import { createTestApp } from '@marmeon/testing';
import { expect, it } from 'vitest';
import application from '../../bootstrap/app.ts';
import { UserFactory } from '#modules/auth';
import { SendInvoiceReminderJob } from './jobs/SendInvoiceReminderJob.ts';
it('sends the reminder five minutes later', async () => {
const app = await createTestApp(application, { database: 'refresh' });
const ada = await app.factory(UserFactory).create();
await app.actingAs(ada).post('/billing/reminders').assertRedirect();
app.queue.assertDispatched(SendInvoiceReminderJob, (_payload, job) => job.delaySeconds === 300);
expect(await app.queue.work()).toMatchObject({ processed: 0 });
app.travel({ minutes: 5 });
expect(await app.queue.work()).toMatchObject({ processed: 1, failed: 0 });
});A job that is released with a backoff waits the same way, so a test of its retries travels between two calls of work(). The
fakes page covers the queue fake.
The schedule and the clock
app.schedule.run(time) moves the clock to time before it runs what is due, so a task sees the minute it runs in. A second
run() later catches up what was missed between the two, as the scheduler does after a pause. The fakes
page shows a test.