Testing
Introduction
Plinth is built so that most tests need no network, no real database server and no waiting. Each feature that touches the outside world has either an in-memory driver, a fake that records what happened instead of doing it, or an injectable clock. This page shows how to run tests, how to swap real services for fakes, and how to assert on what the code under test did.
Tests run with Vitest. The plain-TypeScript examples below work in any Vitest project. The framework's own packages are tested the same way, with the fakes described here.
Running tests
A generated application already has Vitest installed and a test script that runs vitest run:
pnpm testIt also contains a tests/feature directory for tests that boot the application and a tests/unit directory for tests of isolated classes. The generated feature test boots the real application and checks its configuration:
import { describe, expect, it } from 'vitest'
import { createApplication } from '../../src/bootstrap/app.js'
describe('application', () => {
it('boots and exposes configuration', async () => {
const app = await createApplication()
expect(app.config.get('app.name')).toBeTruthy()
})
})In your own package, install Vitest and add the script:
pnpm add -D vitest{
"scripts": {
"test": "vitest run"
}
}Fakes versus in-memory drivers
Two kinds of test double appear throughout the framework, and they suit different tests.
An in-memory driver is a real implementation that keeps its data in memory: the array cache store, the array queue, the in-memory SQLite connection, the array mail transport. The code runs the real logic and you inspect the result afterwards.
A fake replaces a service entirely. It records each call instead of performing it and gives you assert* methods that throw when an expectation is not met. Use fakes when you want to prove that your code sent a mail, dispatched a command or called an API, without any of it happening.
The fakes the framework ships are:
| Feature | Fake | Created with |
|---|---|---|
FakeMailer | fake() from @plinthjs/mail | |
| Command bus | FakeBus | fake() from @plinthjs/bus |
| Events | FakeDispatcher | dispatcher.fake() |
| Notifications | FakeNotificationSender | NotificationSender.fake() or fake() |
| Filesystem | FakeDisk | manager.fake(name?) or fake() from @plinthjs/storage |
| HTTP client | FakeHttp | new FakeHttp() or fakeFetch(...) |
| Processes | ProcessFake | Process.fake(stubs?) |
| Sleeping | the Sleep fake mode | Sleep.fake() |
| Broadcasting | BroadcastFake (also named ArrayBroadcaster) | new BroadcastFake() |
The next sections cover each one.
Swapping a fake into your code
Fakes are plain objects. The simplest way to use one is to accept the service as a constructor argument (dependency injection) and pass the fake in a test. If your code resolves services from the container, bind the fake there instead:
import { Container } from '@plinthjs/core'
import { fake } from '@plinthjs/mail'
const app = new Container()
const mailer = fake()
app.instance('mailer', mailer)If your code uses a facade, point the facades at the container once with Facade.setContainer(app) and replace the service behind the facade with Facade.swap(token, fake), which rebinds the token on the container and returns your fake. Reset with Facade.clearContainer() in afterEach so tests stay independent.
import { Container, Facade } from '@plinthjs/core'
const app = new Container()
Facade.setContainer(app)
const mailer = Facade.swap('mailer', fake())
// ...exercise the code, then:
Facade.clearContainer()Mail
FakeMailer stands in for a real mailer. Sending (send, or to(...).send(...)) records the mailable on sent, and queue and later (or to(...).queue(...)) record it on queued. Nothing reaches a transport.
import { fake, Mailable } from '@plinthjs/mail'
class OrderShipped extends Mailable {
constructor(public readonly orderId: number) {
super()
}
}
const mailer = fake()
await mailer.to('ada@example.com').send(new OrderShipped(5))
await mailer.to('grace@example.com').queue(new OrderShipped(6))
mailer.assertSent(OrderShipped, (mail) => mail.orderId === 5)
mailer.assertSentCount(1, OrderShipped)
mailer.assertQueued(OrderShipped)
mailer.assertNotSent(OrderShipped, (mail) => mail.orderId === 99)
mailer.assertNothingQueued() // throws here: one mailable was queuedThe full set is assertSent, assertNotSent, assertNothingSent, assertSentCount, assertQueued, assertNotQueued and assertNothingQueued. The class and predicate arguments are optional and narrow the match. The recorded mailables are kept untouched and build() is not run, so assert on the fields you set in the constructor or inspect mailer.sent[0].
To test the real rendering instead, use a real Mailer with the in-memory ArrayTransport and read transport.sent or transport.last():
import { ArrayTransport, Mailer } from '@plinthjs/mail'
const transport = new ArrayTransport()
await new Mailer(transport).send(new OrderShipped(1).to('ada@example.com'))
transport.last()?.to // => [{ email: 'ada@example.com' }]See Mail.
Queues and the command bus
For queued jobs, use the in-memory ArrayQueue with a Dispatcher. Dispatching only enqueues; work() runs the due jobs and returns a summary.
import { ArrayQueue, Dispatcher, Job } from '@plinthjs/queue'
class SendReceipt extends Job {
ran = false
override async handle(): Promise<void> {
this.ran = true
}
}
const queue = new ArrayQueue()
const dispatcher = new Dispatcher(queue)
const job = new SendReceipt()
await dispatcher.dispatch(job)
queue.size() // => 1
job.ran // => false
await queue.work() // => { processed: 1, failed: 0 }
job.ran // => trueTo test failure handling, give the queue a failed-job store and set tries on the job. A job that exhausts its attempts is recorded rather than thrown:
import { ArrayFailedJobStore, ArrayQueue } from '@plinthjs/queue'
const failer = new ArrayFailedJobStore()
const queue = new ArrayQueue({ failer })
await queue.push(new AlwaysFails()) // a job with tries = 2 whose handle() throws
await queue.work() // => { processed: 0, failed: 1 }
failer.jobs.length // => 1
queue.failed[0]?.attempts // => 2Delayed jobs depend on a clock, which you control by passing now (epoch milliseconds):
let now = 1_000_000
const queue = new ArrayQueue({ now: () => now })
await queue.later(60, new SendReceipt())
await queue.work() // => { processed: 0, failed: 0 } (not due yet)
now += 61_000
await queue.work() // => { processed: 1, failed: 0 }To prove that code dispatched a command without running its handler, use FakeBus:
import { fake } from '@plinthjs/bus'
class CreateUser {
constructor(public readonly name: string) {}
}
const bus = fake()
await bus.dispatch(new CreateUser('ada'))
bus.assertDispatched(CreateUser, (command) => command.name === 'ada')
bus.assertDispatchedTimes(CreateUser, 1)
bus.assertNotDispatched(CreateUser, (command) => command.name === 'grace')
bus.assertNothingDispatched() // throws herebus.dispatched holds every recorded command, and commands in a chain([...]) are recorded in order. dispatch, dispatchNow, dispatchSync and dispatchToQueue all just record. See Queues.
Events
dispatcher.fake() returns a FakeDispatcher. Events dispatched on it are recorded and no listener runs. Event names are strings.
import { Dispatcher } from '@plinthjs/events'
const events = new Dispatcher().fake()
await events.dispatch('user.created', { id: 1 })
events.assertDispatched('user.created', (payload) => (payload as { id: number }).id === 1)
events.assertDispatchedTimes('user.created', 1)
events.assertNotDispatched('user.deleted')
events.dispatched('user.created') // => [{ id: 1 }]
events.hasDispatched('user.created') // => true
events.assertNothingDispatched() // throws hereIf you only want to observe real dispatching, register a listener on a real dispatcher instead. See Events.
Notifications
NotificationSender.fake() (or fake() from @plinthjs/notifications) returns a FakeNotificationSender. It records each notification per recipient with the channels via() returned, and no channel runs.
import { MailMessage, Notification, NotificationSender } from '@plinthjs/notifications'
import type { Notifiable } from '@plinthjs/notifications'
class User implements Notifiable {
constructor(
public id: number,
public email: string,
) {}
routeNotificationFor(channel: string): unknown {
return channel === 'mail' ? this.email : undefined
}
getKey(): number {
return this.id
}
}
class Welcome extends Notification {
via(): string[] {
return ['mail']
}
override toMail(): MailMessage {
return new MailMessage().subject('Welcome')
}
}
const sender = NotificationSender.fake()
const user = new User(1, 'ada@example.com')
await sender.send(user, new Welcome())
sender.assertSentTo(user, Welcome)
sender.assertSentOnChannel('mail', Welcome)
sender.assertSentTimes(Welcome, 1)
sender.assertCount(1)
sender.assertNotSentTo(new User(2, 'grace@example.com'), Welcome)Recipients are compared by class and getKey(), so a different instance of the same user counts as the same recipient. sentNotifications(Welcome) returns the matching records for your own checks, and assertNothingSent() is available too. See Notifications.
Storage
FakeDisk is an in-memory disk with three extra assertions. A FilesystemManager can replace one of its disks with a fake and return it:
import { FilesystemManager } from '@plinthjs/storage'
const storage = new FilesystemManager()
const disk = storage.fake() // replaces the default disk; pass a name to replace another
await storage.disk().put('avatars/a.png', 'bytes')
await disk.assertExists('avatars/a.png')
await disk.assertMissing('avatars/b.png')
await disk.assertCount('avatars', 1) // direct children; pass true as a third argument for recursionThe assertions are async and throw with a message that lists the offending paths. You can also create a disk on its own with fake() from @plinthjs/storage, which accepts the same options as the in-memory disk (for example { urlBase: '/storage' }). For a manager whose default disk is an ordinary in-memory disk, memoryFilesystem() is a shortcut. See Filesystem.
HTTP client
The HTTP client takes a fetch function as an option, so tests give it a fake one. FakeHttp exposes fetch, records every request and answers from the handlers you add. With no matching handler it returns an empty 200.
import { FakeHttp, Http } from '@plinthjs/http-client'
const fake = new FakeHttp().respond(
{ status: 200, body: { name: 'Ada' } },
{ method: 'GET', urlContains: '/users/1' },
)
const response = await Http({ fetch: fake.fetch }).get('https://api.example.com/users/1')
response.status() // => 200
response.json() // => { name: 'Ada' }
fake.assertSent((req) => req.method === 'GET' && req.url.endsWith('/users/1'))
fake.assertSentCount(1)
fake.lastRequest()?.headers // lower-cased header namesA response spec is { status?, body?, headers? }. An object body is serialised as JSON with a JSON content type. Handlers are tried in the order you add them, and the first that returns a spec wins.
respond(spec, { method?, urlContains? })answers matching requests.handle(fn)takes a function from the recorded request to a spec (orundefinedto pass).sequence([spec1, spec2, ...])returns one spec per call and repeats the last, which is how you test retries:new FakeHttp().sequence([{ status: 503 }, { status: 200 }]).assertNotSent(fn),assertNothingSent(),count()andrequestsround out the assertions.
For a quick one-off, fakeFetch(handler) returns a ready fetch function.
Processes
Process.fake(stubs?) swaps the process runner for a recorder. No operating system process is spawned. Stubs map a command line to a result, and * matches any run of characters. Without a matching stub, a command succeeds with empty output.
import { clearFake, Process } from '@plinthjs/process'
import { afterEach } from 'vitest'
afterEach(() => {
clearFake() // restore the real runner
})
const fake = Process.fake({
'git status': { output: 'nothing to commit' },
'deploy *': { exitCode: 13, errorOutput: 'permission denied' },
})
const result = await Process.run('git status')
result.output() // => 'nothing to commit'
fake.assertRan('git *')
fake.assertRanTimes('git status', 1)
fake.assertNotRan('npm *')
fake.assertNothingRan() // throws hereA stub can also be a function that receives the command line and returns a result built with Process.fakeResult({ output, errorOutput, exitCode }). Call fake.preventStrayProcesses() to make any command without a matching stub throw instead of quietly succeeding, which catches commands you forgot to stub.
WARNING
Process.fake installs a process-wide runner. Always call clearFake() in afterEach, or the fake leaks into other tests in the same file or worker. See Process.
Sleeping and time
Sleep.fake() switches the whole Sleep module into a mode where nothing waits. Each requested duration is recorded, in milliseconds. This turns retry loops and polling code from slow tests into instant ones.
import { Sleep } from '@plinthjs/support'
import { afterEach, it } from 'vitest'
afterEach(() => {
Sleep.restore()
})
it('backs off between attempts', async () => {
Sleep.fake()
await Sleep.for(2).seconds()
await Sleep.for(500).milliseconds()
Sleep.assertSequence([2000, 500])
Sleep.assertSleptTimes(2)
Sleep.assertSlept((ms) => ms === 500)
// Sleep.assertNeverSlept() would throw here
})Sleep.restore() returns to real sleeping and clears the record. For the real path you can also replace the timer with Sleep.useTimer(async (ms) => { ... }).
The framework has no global "freeze time" switch. Instead, everything that reads the time accepts an injected clock, a function that returns epoch milliseconds. Pass your own and move it forward by hand. This works for the cache, rate limiter, queue, session store and recorders:
import { arrayCache } from '@plinthjs/cache'
import { RateLimiter } from '@plinthjs/rate-limiter'
let now = 0
const clock = (): number => now
const cache = arrayCache({ now: clock })
await cache.put('token', 'abc', 10) // ttl in seconds
await cache.get('token') // => 'abc'
now = 11_000
await cache.get('token') // => null (expired)
const limiter = new RateLimiter({ now: clock })
limiter.hit('login', 60)
limiter.hit('login', 60)
limiter.tooManyAttempts('login', 2) // => true
limiter.availableIn('login') // => 60
now += 61_000
limiter.attempts('login') // => 0 (the window elapsed)See Cache and Rate Limiting.
Cache, session and database
The in-memory implementations need no fakes at all:
import { arrayCache } from '@plinthjs/cache'
import { arraySession } from '@plinthjs/session'
import { sqliteConnection } from '@plinthjs/database'
const cache = arrayCache() // a Repository over the in-memory ArrayStore
const { manager, store } = arraySession() // a SessionManager over the in-memory store
const db = sqliteConnection() // an in-memory SQLite databasesqliteConnection() with no arguments gives you a fresh in-memory database for each test, so you can create tables and seed rows without touching a file:
await db.statement('create table users (id integer primary key, name text)')
await db.table('users').insert([{ name: 'Ada' }])
await db.table('users').count() // => 1See Cache, Session, Database and Seeding.
Broadcasting
BroadcastFake (also exported as ArrayBroadcaster) records broadcasts instead of publishing them. Channels are stored by their wire names.
import { BroadcastFake } from '@plinthjs/broadcasting'
const broadcaster = new BroadcastFake()
// ...exercise code that broadcasts through it, then:
broadcaster.assertBroadcasted('order.shipped')
broadcaster.assertBroadcastedOn('orders.5', 'order.shipped')
broadcaster.assertNotBroadcasted('order.cancelled')
broadcaster.broadcasts() // => [{ channels: ['orders.5'], event: 'order.shipped', payload: {...} }]assertBroadcasted and assertNotBroadcasted accept either an event name or a predicate over the recorded broadcast, and assertNothingBroadcasted() is available as well. See Broadcasting.
Feature flags
Feature flags need no fake. Define the flag with a resolver and force a value with activate or deactivate, which bypass the resolver. Reads are async:
import { FeatureManager } from '@plinthjs/feature-flags'
const features = new FeatureManager()
features.define('new-checkout', () => false)
features.activate('new-checkout')
await features.active('new-checkout') // => trueSee Feature Flags.
Testing a route in-process
You do not need a server or a socket to test a route. Build a Router, wrap it in an HttpKernel, and call kernel.handle() with a Request constructed in memory. The result is a Response whose status, headers and body you can assert on.
import { Application } from '@plinthjs/core'
import { HttpKernel, Request, Response, Router } from '@plinthjs/http'
import { expect, it } from 'vitest'
it('returns a user', async () => {
const router = new Router()
router.get('/users/{id}', (request) =>
Response.json({ id: request.param('id'), page: request.query('page') }),
)
const kernel = new HttpKernel(router, { container: new Application({ runningInConsole: false }) })
const response = await kernel.handle(new Request({ method: 'GET', url: '/users/7?page=2' }))
expect(response.status).toBe(200)
expect(JSON.parse(response.body ?? '')).toEqual({ id: '7', page: '2' })
})A Request takes method, url (including the query string), headers (names are lower-cased) and a raw string body. For a JSON request, set the content type and stringify the body:
const request = new Request({
method: 'POST',
url: '/users',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ email: 'ada@example.com' }),
})Unknown paths return a 404 response rather than throwing, so you can assert on that too.
To test a controller, register it on the router and give the kernel a container that can build it. Combine this with the fakes above by constructing the controller with a fake and binding that instance, so the route under test talks to the fake:
import { Application } from '@plinthjs/core'
import { Controller, HttpKernel, Request, Response, Router } from '@plinthjs/http'
import { fake, Mailable } from '@plinthjs/mail'
class Welcome extends Mailable {}
class UserController extends Controller {
constructor(private readonly mailer: ReturnType<typeof fake>) {
super()
}
async store(request: Request): Promise<Response> {
const email = String(request.input('email'))
await this.mailer.to(email).send(new Welcome())
return Response.json({ created: email }, 201)
}
}
it('creates a user and sends a welcome mail', async () => {
const app = new Application({ runningInConsole: false })
const mailer = fake()
app.instance(UserController, new UserController(mailer))
const router = new Router()
router.post('/users', [UserController, 'store'])
const kernel = new HttpKernel(router, { container: app })
const response = await kernel.handle(
new Request({
method: 'POST',
url: '/users',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ email: 'ada@example.com' }),
}),
)
expect(response.status).toBe(201)
mailer.assertSent(Welcome)
})In a generated application, routes are registered by functions such as registerWebRoutes(router) in src/routes/web.ts. A feature test can create a Router, call that function, wrap the router in an HttpKernel with the application as its container, and send requests exactly as above. See Routing, Controllers, Requests and Responses.
The same approach tests a warm persistent worker: call worker.handle(request) instead of kernel.handle(request).
Tips
- Keep one fake per test. Create it inside the test (or in
beforeEach) so recorded calls never leak between tests. - Fakes that install a global (
Process.fake,Sleep.fake,Facade.setContainer) need a matching reset (clearFake,Sleep.restore,Facade.clearContainer) inafterEach. - Assertion methods throw ordinary errors, so they work in any runner. In Vitest you can also wrap them:
expect(() => mailer.assertSent(OrderShipped)).toThrow(). - Prefer injecting dependencies through constructors. A class that receives its mailer, queue or HTTP client can be tested with a fake and no container at all.
- For search, the in-memory
CollectionEngineis the default engine, so Search tests need no setup. The Inspector and Monitor recorders take injectable clocks and id generators for exact assertions.