X · Testing
Fakes
On this page
Introduction
A test should not send mail, fill a real queue or write to S3. createTestApp() replaces those services with fakes: each one
records what the app asked of it, checks it as the real service would, and lets the test assert on it. The fakes are in place by
default, as soon as the app has the package:
| Fake | Replaces | Keep the real service with |
|---|---|---|
app.mail | The Mailer. Records mails instead of sending them. | mail: 'real' |
app.queue | The Queue. Records jobs, and work() runs them. | queue: 'real' |
app.notifications | Notifications. Records notifications, and deliver() delivers them. | notifications: 'real' |
app.chat | The ChatNotifier. Records chat messages instead of posting them. | chat: 'real' |
app.http | The HttpClient. Answers outgoing requests from replies you register, and refuses private addresses as the real client does. | http: 'real' |
app.storage | Storage. Every disk lives in memory. | storage: 'real' |
app.events | Nothing. Records every event; listeners still run unless you hold them back. | events: 'real', the default |
app.broadcast | Nothing. Records every live hint, which still reaches the streams. Needs @marmeon/live. | always in place |
app.schedule | Nothing. Runs the schedule on the test's clock. Needs @marmeon/scheduler. | always in place |
fakeOAuth(app) for social login is a function, not an app.* getter.
A getter whose package the app lacks, or whose fake the test turned off, says so:
app.queue needs @marmeon/queue in the app (and not createTestApp(…, { queue: 'real' })).A test reaches the fakes through app. The classes behind the mail, queue, notifications, chat, storage, HTTP client and schedule fakes (MailFake,
QueueFake, NotificationFake, ChatFake, StorageFake, HttpClientFake, ScheduleTester) are in the /testing subpath of their package, for the one who types a
variable with them: import type { QueueFake } from '@marmeon/queue/testing'. The same holds for BroadcastTester and LiveStreamReader (@marmeon/live/testing) and for DevtoolsTester (import type { DevtoolsTester } from '@marmeon/devtools/testing'). A *Tester drives or reads the real
service: ScheduleTester, BroadcastTester and DevtoolsTester. createTestApp() makes every fake: a test does not construct
MailFake itself, its constructor is not part of the API.
The devtools record into memory with devtools: true, as the devtools page shows, and the clock is the
subject of the time page.
The mail fake composes every mail as the real mailer does, so a broken template, a relative link or an invalid address fails the
test. It keeps mails sent at once, with mailer.send(), apart from queued ones, with mailer.queue():
import { createTestApp } from '@marmeon/testing';
import { expect, it } from 'vitest';
import application from '../../bootstrap/app.ts';
import { VerifyEmailMail } from './mail/VerifyEmailMail.ts';
it('mails the new account its verification link', async () => {
const app = await createTestApp(application, { database: 'refresh' });
await app.post('/register', {
form: { name: 'Katherine Johnson', email: 'kj@example.com', password: 'orbital mechanics', password_confirmation: 'orbital mechanics' },
});
app.mail.assertNothingQueued();
await app.queue.work();
app.mail.assertQueued(VerifyEmailMail, (_mail, message) => message.to[0]!.address === 'kj@example.com');
const [queued] = app.mail.queued(VerifyEmailMail);
expect(queued!.message.text).toContain('/email/verify/');
});The registration only queues a listener, so no mail exists until work() runs it. Each recorded mail comes with the mailable,
its composed message and, for a queued one, its queue options:
| Assertion | Passes when |
|---|---|
assertSent(Mail, filter) | A mail of that class was sent, matching filter(mail, message) when given. |
assertSentCount(Mail, n) | Exactly n of that class were sent. |
assertNotSent(Mail, filter), assertNothingSent() | None of that class, or no mail at all, was sent. |
assertQueued(Mail, filter) | A mail of that class was queued, matching filter(mail, message, options) when given. |
assertQueuedCount(Mail, n) | Exactly n of that class were queued. |
assertNotQueued(Mail, filter), assertNothingQueued() | None of that class, or no mail at all, was queued. |
sent(Mail, filter) and queued(Mail, filter) return the records themselves. assertSent() on a mail that was queued fails, and
its message says the mail was queued. The fake does not put queued mails on the queue: with mail: 'real' they go through the
queue and its marmeon.mail job like in production. The mail page covers writing mails.
send() resolves with a made-up message id (<fake-1@marmeon.test>), different for every mail. failNext(error, times) makes
the next send fail, to test what the app does when the provider is down: app.mail.failNext(new Error('smtp down')) fails the
next send() with that error, shows the failure on the mail.send channel, and records nothing for it. Without an error it
fails with The fake mailer failed this send.; times fails that many sends in a row, then sends work again.
failNext() reaches send() only: the fake takes a queued mail without delivering it. An outage on the way through the queue,
the retries and the failed jobs, is tested with mail: 'real' and queue: 'real' and a MailTransport of the test's own that
throws, bound with override: (c) => c.instance(MailTransport, transport). The tests of the web app's
modules/auth/queued-mails.test.ts show the pattern.
Outgoing requests
The fake of @marmeon/fetch opens no connection. You tell it what a server answers, and it records what the app sent:
import { createTestApp } from '@marmeon/testing';
import { expect, it } from 'vitest';
import application from '../../bootstrap/app.ts';
import { UserFactory } from '#modules/auth';
it('pings the address of the hook, and refuses the metadata address with no reply called', async () => {
const app = await createTestApp(application, { database: 'refresh' });
const editor = await app.factory(UserFactory).create();
app.http.respond(/.*/, () => new Response('ok'));
await app.actingAs(editor).post('/hooks/ping', { json: { url: 'https://hooks.example.com/in' } }).assertOk();
const [request] = app.http.requests;
expect(await request!.clone().json()).toEqual({ ping: true });
await app.actingAs(editor).post('/hooks/ping', { json: { url: 'http://169.254.169.254/latest/meta-data' }, headers: { accept: 'application/json' } }).assertUnprocessable();
app.http.assertSentCount(1);
});A request nobody answered throws FetchError('network') that names the request (no fake response for GET https://… — add app.http.respond(…)), so a test never reaches the network. The fake judges the address before it looks for a reply, with the rules and
the FETCH_ALLOWED_ADDRESSES of the real client: an IP address, localhost and a host mapped with dns() are refused when they are not
public, and a host nobody mapped counts as public. A redirect is followed as in production, and each hop is judged and answered on its own.
| Method | Effect |
|---|---|
respond(match, reply) | Answers the requests match matches: an address as text (written as fetch writes it), a pattern for it or a function of the Request. reply is a Response, read once and copied for every request (its body must end, and your own Response stays unread), or a function that returns a new one or a promise of one: a body that streams belongs in the function, (request) => new Response(stream, …). The latest reply that matches wins. |
dns(host, addresses) | Makes host stand for addresses, as the resolver would; an empty list means the host does not resolve (network). |
failNext(reason, times) | Fails the next requests that pass the address policy with a FetchError of reason (default network, times default 1). |
requests | The requests that passed the address policy, in order, each with its body: await request.clone().text(). A refused request is not among them. |
assertSent(match), assertSentCount(n), assertNothingSent() | Pass when a request matches, exactly n were sent, or none was. |
A text that is no address in respond() or assertSent(), a dns() key that is not a bare host name or IP address (a port, user, path, query or fragment is refused), and a failNext() with another reason or
a times that is not a whole number of 1 or more throw a TypeError. The HTTP client page shows the client.
Queue
The queue fake checks a dispatch as the real queue does, against the job's schema and the transaction around it, and records it
instead of queuing it. app.queue.work() then runs the jobs for real, in the test's process:
import { createTestApp } from '@marmeon/testing';
import { expect, it } from 'vitest';
import application from '../../bootstrap/app.ts';
import { UserFactory } from './factories/UserFactory.ts';
import { SendPasswordResetLinkJob } from './jobs/SendPasswordResetLinkJob.ts';
import { ResetPasswordMail } from './mail/ResetPasswordMail.ts';
it('queues a job for every address, and mails only the known one', async () => {
const app = await createTestApp(application, { database: 'refresh' });
const ada = await app.factory(UserFactory).create();
await app.post('/forgot-password', { form: { email: ada.email } });
await app.post('/forgot-password', { form: { email: 'nobody@example.com' } });
app.queue.assertDispatchedTimes(SendPasswordResetLinkJob, 2);
app.queue.assertDispatched(SendPasswordResetLinkJob, { email: ada.email });
expect(await app.queue.work()).toMatchObject({ failed: 0 });
app.mail.assertQueuedCount(ResetPasswordMail, 1);
});work() runs every job that is due, with the container's injection, a scope per attempt, retries, chains, job middleware and job
events, and jobs that jobs dispatch. It resolves with what it did: processed, failed, released, and the reason it stopped.
work({ queues: ['mail'], maxJobs: 1 }) runs only some queues, or only so many jobs. A job dispatched with a delay, or released
with a backoff, waits until the test's clock reaches it: app.travel({ minutes: 5 }), then work() again. Inside connections.transaction(),
a dispatch is recorded with the commit, and a rollback records nothing. That holds for queue.using(trx) of that transaction too. Only a transaction nothing reports on is different (one your code began itself with Kysely, or one of a second connection, see queues): nothing reports its end, so the fake records the job at once and keeps it after a rollback, unlike the real queue, whose row goes with the rollback. Test a rollback through connections.transaction().
| Assertion | Passes when |
|---|---|
assertDispatched(Job, match, { unique }) | The job was dispatched, matching a part of the payload or a function when given, with that unique key when given. |
assertDispatchedTimes(Job, n, match) | It was dispatched exactly n times. |
assertNotDispatched(Job, match), assertNothingDispatched() | It was not dispatched, or nothing was. |
assertChained([JobA, [JobB, payload]]) | A chain of exactly these jobs was dispatched, in this order. |
assertListenerQueued(Listener, match) | A queued listener was queued. |
assertListenerNotQueued(Listener, match) | It was not. |
dispatched(Job, match) returns the dispatches themselves, with their payload, id, queue, connection, delaySeconds, inTransaction, unique key (unique.key, unique.forSeconds, unique.until) and the chain of jobs after it. inTransaction is true for a job dispatched inside connections.transaction() or through queue.using(trx). Both are recorded with the commit, so a job whose transaction rolls back is never recorded; only a transaction nothing reports on records at once (see above). pending() lists
the jobs still waiting, failed() the jobs work() recorded as failed, and size(queue) counts a queue. A unique job takes its
lock in the app's cache as on a real queue, so a second dispatch with the same key is not recorded until work() ran the first.
The queues page covers jobs.
Notifications
The notification fake checks a send as the real service does: the notification is registered, a resolver knows the recipient's
type, and the data matches the schema. It records the send, and deliver() delivers what was recorded through the app's
channels:
import { Inbox } from '@marmeon/notifications';
import { createTestApp } from '@marmeon/testing';
import { expect, it } from 'vitest';
import application from '../../bootstrap/app.ts';
import { UserFactory } from '#modules/auth';
import { NoteFactory } from './factories/NoteFactory.ts';
import { NoteSharedNotification } from './notifications/NoteSharedNotification.ts';
it('notifies the person a note is shared with, once', async () => {
const app = await createTestApp(application, { database: 'refresh' });
const ada = await app.factory(UserFactory).create();
const bob = await app.factory(UserFactory).create({ email: 'bob@example.com' });
const note = await app.factory(NoteFactory).create({ user_id: ada.id });
await app.actingAs(ada).post(`/notes/${note.id}/share`, { form: { email: 'bob@example.com' } }).assertRedirect();
app.notifications.assertSentTimes({ type: 'user', id: bob.id }, NoteSharedNotification, 1);
app.notifications.assertNotSent({ type: 'user', id: ada.id }, NoteSharedNotification);
await app.notifications.deliver();
expect(await app.make(Inbox).count({ type: 'user', id: bob.id })).toBe(1);
});| Assertion | Passes when |
|---|---|
assertSent(recipient, Notification, match) | It was sent to the recipient, matching a part of the data or a function when given. |
assertSentTimes(recipient, Notification, n) | It was sent to the recipient exactly n times. |
assertNotSent(recipient, Notification, match), assertNothingSent() | It was not sent to the recipient, or nothing was. |
A recipient is { type, id }. sent(Notification, recipient, match) returns the records. The fake records send() and
sendNow() alike. deliver() delivers each recorded notification once, oldest first, as a worker would: the database channel
writes its row and the mail channel queues its mail on the mail fake, and the chat channel records its message on app.chat. It resolves with each notification's id and outcome. Inside
a transaction a notification is recorded with the commit. With notifications: 'real', send() queues a job, and
app.queue.work() delivers it. The notifications page covers notifications.
Chat
The chat fake of @marmeon/chat-notifications checks a message as the real notifier does: a destination CHAT_WEBHOOKS does not
list, an address the driver refuses and a bad message fail the test. It then records the message and posts nothing. A test uses a
made-up address in the driver's shape, because nothing is posted. queue() needs the queue services of the app, like the real one, and a test app that has them
records the message without queueing a job. A notification that goes through the chat channel reaches the fake when deliver() delivers it:
import { createTestApp } from '@marmeon/testing';
import { it } from 'vitest';
import application from '../../bootstrap/app.ts';
import { UserFactory } from '#modules/auth';
import { PaymentFailedNotification } from './notifications/PaymentFailedNotification.ts';
it('tells the ops channel about a declined payment', async () => {
const app = await createTestApp(application, {
database: 'refresh',
env: { CHAT_DRIVER: 'slack', CHAT_WEBHOOKS: 'ops=https://hooks.slack.com/services/test-ops' },
});
const buyer = await app.factory(UserFactory).create();
await app.notifications.send({ type: 'user', id: buyer.id }, PaymentFailedNotification, { order: 'o-1' });
await app.notifications.deliver();
app.chat.assertQueued({ to: 'ops', title: 'Payment failed' }).assertQueuedCount(1);
});| Assertion | Passes when |
|---|---|
assertQueued(match), assertQueuedCount(n), assertNothingQueued() | A message was queued that matches, exactly n were, or none was. |
assertSent(match), assertSentCount(n), assertNothingSent() | The same for the messages send() posted. |
A match is an object with a to, a title or a text, or a function of the recorded message; without one, any message
matches. A destination is compared as it is sent, so { url, driver: undefined } equals { url }.
queued and sent return the records, each with to, content, options and inTransaction, which says whether the call was made
inside a transaction.
A message queued inside a transaction is recorded when the transaction commits, and never after a rollback.
failNext(error, times) makes the next send() calls throw, a ChatDeliveryError of the reason unavailable by default. It does not
touch queue(), because the failure of a queued message belongs to its job.
A failed assertion names a destination by its name or host, never by its address.
With chat: 'real' the configured driver posts and app.chat throws. app.http answers the request the driver makes, and
app.queue.work() runs a queued message. The chat notifications page covers the package.
Storage
The storage fake turns every configured disk into a disk in memory, with the disk's name, visibility and URL. Every test starts with empty disks, the app's routes serve the files, and temporary links are signed for real:
import { createTestApp } from '@marmeon/testing';
import { it } from 'vitest';
import application from '../../bootstrap/app.ts';
import { UserFactory } from '#modules/auth';
import { NoteFactory } from './factories/NoteFactory.ts';
it('exports the notes as JSON to the private disk', async () => {
const app = await createTestApp(application, { database: 'refresh' });
const ada = await app.factory(UserFactory).create();
await app.factory(NoteFactory).create({ user_id: ada.id, title: 'Groceries' });
await app.actingAs(ada).post('/notes/download').assertRedirect();
const disk = app.storage.disk('local');
disk.assertCount(1, 'exports');
disk.assertExists(`exports/notes-${ada.id}.json`, (bytes) => new TextDecoder().decode(bytes).includes('"Groceries"'));
app.storage.disk('public').assertCount(0);
});| Assertion | Passes when |
|---|---|
assertExists(key, contents) | The file exists, with these contents when given: text, bytes, or a function of the bytes. |
assertMissing(key) | The file does not exist. |
assertCount(n, directory) | The disk, or the directory and everything under it, holds exactly n files. |
files() lists every key on a disk. A disk name is checked by the compiler as in the app. app.upload() sends a file through
the real upload target onto the fake, as the HTTP tests page shows. The file storage
page covers disks.
Events
Every test app records the events it dispatches. Their listeners run as usual, unless the test holds them back: events: 'fake'
holds back every listener, and a list of event classes holds back the listeners of those classes and their subclasses. A
held-back event is recorded and nothing else, so its listeners neither run nor are queued:
import { Registered } from '@marmeon/auth';
import { createTestApp } from '@marmeon/testing';
import { it } from 'vitest';
import application from '../../bootstrap/app.ts';
import { SendEmailVerification } from './listeners/SendEmailVerification.ts';
it('announces a registration', async () => {
const app = await createTestApp(application, { database: 'refresh', events: [Registered] });
await app.post('/register', {
form: { name: 'Katherine Johnson', email: 'kj@example.com', password: 'orbital mechanics', password_confirmation: 'orbital mechanics' },
});
app.events.assertDispatched(Registered, (event) => event.user.email === 'kj@example.com');
app.events.assertListening(Registered, SendEmailVerification);
app.queue.assertListenerNotQueued(SendEmailVerification);
});| Assertion | Passes when |
|---|---|
assertDispatched(Event, match) | The event was dispatched, matching a part of its fields or a function when given. |
assertDispatchedTimes(Event, n, match) | It was dispatched exactly n times. |
assertNotDispatched(Event, match), assertNothingDispatched() | It was not dispatched, or no event was. |
assertListening(Event, Listener) | The listener is registered for the event, queued or not. |
dispatched(Event, match) returns the events themselves, oldest first. The dispatch assertions match subclasses of the class too.
The events page covers events and listeners.
Live updates
Live hints go out in a test as in production: the streams a test opens receive them. app.broadcast records each hint once it
went out, after its transaction committed:
import { UserFactory } from '#modules/auth';
import { createTestApp } from '@marmeon/testing';
import { expect, it } from 'vitest';
import application from '../../bootstrap/app.ts';
it('tells the other tabs on the profile, and only after a valid change', async () => {
const app = await createTestApp(application, { database: 'refresh' });
const ada = await app.factory(UserFactory).create();
const stream = await app.actingAs(ada).live(`/users/${ada.id}`);
await stream.hello();
await app.actingAs(ada).expectingJson().post(`/users/${ada.id}/links`, { json: { label: '', url: 'nope' } }).assertUnprocessable();
app.broadcast.assertNothingRefreshed();
await app.actingAs(ada).post(`/users/${ada.id}/links`, { json: { label: 'Blog', url: 'https://ada.example' } }).assertRedirect();
app.broadcast.assertRefreshed(`users.${ada.id}`, { only: ['profile'], times: 1 });
await stream.waitFor(1);
expect(stream.hints).toEqual([{ channel: `users.${ada.id}`, only: ['profile'], seq: 1 }]);
});assertRefreshed(channel, { only, times }) passes when the channel was refreshed, with exactly those props and that many times
when given. It counts the hints that went out: equal hints of one transaction are one, however many times refresh() was called. assertNotRefreshed(channel) and assertNothingRefreshed() check the opposite, and refreshed(channel) returns the
records. app.live(path) opens the stream of the page at path as a tab does, signed for the view's session. hello() waits
for the stream's first message, waitFor(n) for n hints (it fails after two seconds; waitFor(n, { timeout: { seconds: 5 }, what: 'the profile hint' }) changes the wait and names it in the failure), and hints holds them. The real-time updates page
explains hints.
LiveStreamReader, what app.live() returns, has these members besides hello(), waitFor() and hints: events, every event so
far as { event, id, data }; status; response, the Response of the stream; ended, whether the stream ended, and closed, a promise that
resolves when it did; close(), which hangs up like a tab that goes away; and, for tests of the stream itself, heartbeats, how many heartbeat
comment lines came, and retryMs, the stream's retry: in milliseconds. waitFor(until) also takes a function that returns true once what the
test waits for has come. app.broadcast.clear() forgets the hints recorded so far.
The schedule
app.schedule runs the app's schedule on the test's clock:
import { AccessTokenStore } from '@marmeon/auth';
import { createTestApp } from '@marmeon/testing';
import { expect, it } from 'vitest';
import application from '../../bootstrap/app.ts';
import { UserFactory } from './factories/UserFactory.ts';
it('prunes expired tokens at night and keeps valid ones', async () => {
const app = await createTestApp(application, { database: 'refresh' });
const ada = await app.factory(UserFactory).create();
app.freeze(Date.parse('2026-10-04T12:00:00Z'));
await app.make(AccessTokenStore).create(ada.id, 'one hour', { abilities: ['*'], expiresIn: { hours: 1 } });
const valid = await app.make(AccessTokenStore).create(ada.id, 'a year', { abilities: ['*'], expiresIn: { days: 365 } });
expect(app.schedule.due('2026-10-05T03:10:00Z')).toContain('auth:prune-tokens');
const results = await app.schedule.run('2026-10-05T03:10:00Z');
expect(results.find((result) => result.task === 'auth:prune-tokens')).toMatchObject({ outcome: 'ran' });
expect((await app.make(AccessTokenStore).list(ada.id)).map((token) => token.id)).toEqual([valid.token.id]);
});| Member | What it does |
|---|---|
tasks | The names of every task. |
due(time) | The names of the tasks due in that minute, by frequency and environment. Conditions are asked only when a task runs. |
run(time) | Moves the clock to time, runs what is due and what was missed since the last run(), and resolves with the results. |
runTask(name) | Runs one task now, as marmeon schedule:test does. |
A time is a Date, epoch milliseconds or an ISO string such as '2026-10-04T03:10:00+02:00'. Each result names its task and
its outcome: ran, skipped or failed. The task scheduling page covers the schedule.
Social login
fakeOAuth(app) of @marmeon/oauth/testing makes every social login provider of the app answer from app.http, so a test signs in through the
real redirect() and callback(): the state, the PKCE check, the nonce, the ID token checks and the confirmation all run. It is not one of the
app.* fakes, since the package does not know what your routes look like; call it in the test, before the request that reads OAuth. The routes
in the example are the ones of your app, as social login shows them. The start and the callback must be one browser, since the flow
lives in its session, so both requests go through app.keepingCookies().
import { fakeOAuth } from '@marmeon/oauth/testing';
import { createTestApp } from '@marmeon/testing';
import { expect, it } from 'vitest';
import application from '../../bootstrap/app.ts';
it('signs a person in with GitHub', async () => {
const app = await createTestApp(application, { database: 'refresh', env: { APP_URL: 'https://app.example.com' } });
const oauth = fakeOAuth(app).user('github', { id: '42', email: 'ada@example.com', emailVerified: true });
const browser = app.keepingCookies();
const start = await browser.post('/auth/github/start').assertStatus(303);
await browser.get(oauth.callbackUrl(start)).assertRedirect('/dashboard');
});| Member | What it does |
|---|---|
fakeOAuth(app, { only }) | Makes every registered provider (or the names in only) active with test credentials, built through the checks of the start. An oidc() provider is replaced by an OpenID Connect fake that keeps its own mapping, any other by a plain OAuth 2.0 one. Throws a TypeError when app.http is not the app's client (http: 'real'). |
user(name, profile) | The next callback of name vouches for profile, and starts a new preparation. Only id (a non-empty string) is required; claims adds ID token claims for an oidc() provider. Call it first. |
reauthenticated(name) | The next callback carries a fresh auth_time. Throws for a provider that cannot confirm anybody. |
staleAuthentication(name, secondsAgo) | The next callback carries an auth_time that long ago, to test a confirmation that is too old. Throws as reauthenticated() does. |
deny(name) | The next callback is error=access_denied. |
callbackUrl(redirect, { state }) | The path and query the provider sends the browser back to, from the Location of the redirect (a response, such as the one of app.post(), a URL or the address as text). state replaces the state, to test a forged callback. Throws when no profile is queued and the provider was not denied. |
authorizations | The authorization requests callbackUrl() was given, as URLSearchParams. |
The providers fall into three groups. GitHub, Discord and your own plain OAuth 2.0 providers never confirm. Google and GitLab are OpenID Connect fakes that do not
confirm either. Microsoft and your own oidc() providers confirm after reauthenticated(). An ID token has no auth_time unless the test asks for it. See testing social login.