Testing strategy
Summary. The kit tests behaviour through public interfaces at four levels (domain, application, adapter, end to end), with the same test data builders at every level. Test doubles are fakes, working in-memory implementations of ports, rather than mocks; a fake is kept honest by passing the same contract suite as the real adapter it stands for. Aggregate specs read given / when / then. The result is a suite where most tests run in milliseconds with no infrastructure, survive refactoring because they assert outcomes rather than calls, and read as business rules. This page explains each choice, says what to test where, and states what the strategy does not cover.
The vocabulary of test doubles
Section titled “The vocabulary of test doubles”"Mock" is often used for any stand-in. Gerard Meszaros's vocabulary, popularised by Martin Fowler, is more precise:
| Double | What it is | Verifies |
|---|---|---|
| dummy | passed but never used | nothing |
| stub | returns canned answers | state, indirectly |
| spy | a stub that records how it was called | calls, after the fact |
| mock | pre-programmed with the calls it expects | calls: the test fails if they differ |
| fake | a working implementation with a shortcut (in memory instead of a database) | state |
The distinction that matters is the last column. A test with mocks asserts an interaction:
"save was called once with this object". A test with a fake asserts an outcome: "the
appointment is stored and cancelled".
Fakes, not mocks
Section titled “Fakes, not mocks”// instead of, with a mock: asserts how the handler talks to its collaboratorsconst appointments = { findById: vi.fn().mockResolvedValue(appointment), save: vi.fn() };// the access check is mocked too: the test now knows every collaborator of the handlerconst access = { authorize: vi.fn().mockResolvedValue(undefined) };const handler = new CancelAppointmentHandler(appointments, access, clock);
await handler.execute(new CancelAppointmentCommand(patient, appointment.id));
expect(appointments.save).toHaveBeenCalledWith(expect.objectContaining({ status: 'cancelled' }));
// write, with a fake: asserts what is true afterwardsconst appointments = new FakeAppointmentRepository();await appointments.save(appointment);
const app = createTestApplication({ modules: [platformTestModule, contextModule('scheduling', schedulingDeclarations), holders], fakes: [fake(AppointmentRepository, appointments)],});
await app.commandBus.execute(new CancelAppointmentCommand(patient, appointment.id));
expect((await appointments.findById(appointment.id))?.status).toBe('cancelled');expect(app.eventBus.published).toMatchObject([{ type: 'scheduling.appointment.cancelled' }]);Why the kit prefers the second form (rule
test/no-mocks, a warning by default):
- Mocks couple tests to the implementation. Rename a method, save in two steps instead of one, load through another finder: behaviour is unchanged, mock-based tests fail. Tests that break on refactoring discourage refactoring.
- Mocks can assert a lie. A mocked repository returns whatever the test says, including things the real one never would. The test passes; production does not.
- Fakes are reusable. One in-memory repository serves every handler spec of the context,
and a failure is a method on the fake (
mailer.failNextWith(...)) rather than a setup repeated in each test. - The architecture makes mocks unnecessary. Every dependency is a port received by constructor; time and identifiers are ports too. A class that needs a module mock to be tested is breaking a purity rule (Clean code).
This is the "classical" school in Fowler's terms. The "mockist" school, described by Freeman and Pryce, uses mocks to discover interfaces while designing outside-in; it is a coherent practice, and its authors also warn against mocking types you do not own. The kit's position is narrower than a doctrine: its ports are already designed and each has a fake, so interaction assertions add coupling without adding information.
The one accepted double that is not a fake: a stub of an outside HTTP API at the network level, in an adapter's integration spec.
A fake is a small class of test/fakes/ that implements the port with a shortcut, and offers
the failures a test needs as methods. The mailer of the notification context of the example,
shortened:
export abstract class Mailer { /** Fails when the provider did not take the mail. */ abstract deliver(address: string, subject: string): Promise<void>;}
// notification/test/fakes/mailer.fake.tsexport class FakeMailer implements Mailer { /** What the provider took, in order: what a spec asserts. */ readonly delivered: { readonly address: string; readonly subject: string }[] = [];
private readonly failures: Error[] = [];
/** The next delivery fails with this error, then the mailer works again. */ failNextWith(error: Error): void { this.failures.push(error); }
async deliver(address: string, subject: string): Promise<void> { const failure = this.failures.shift();
if (failure !== undefined) { throw failure; }
this.delivered.push({ address, subject }); }}A spec then reads like the rule it proves: mailer.failNextWith(new Error('provider unreachable')), send the notification, and expect that nothing was saved and nothing published.
Contract tests keep fakes honest
Section titled “Contract tests keep fakes honest”The weakness of a fake is drift: an in-memory repository that tolerates what PostgreSQL would refuse. The answer is a contract suite: one set of tests written against the port, run against the fake and against the real adapter.
flowchart TB C[Contract suite of the port: save then find, unknown id, update, optimistic concurrency...] C --> F[FakeCalendarRepository, in test/fakes] C --> R[Real adapter on PostgreSQL] F --> H[used by every handler spec] R --> P[used in production]
In code, one call per implementation, with the same expectations. The spec of the calendar repository of the example, shortened:
import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { AggregateRoot, type Repository } from '@ddd-ts-kit/kernel';import { InMemoryRepository } from '@ddd-ts-kit/testing';import { repositoryContract } from '@ddd-ts-kit/testing/contracts';
// from the domain, the builders and the test database of the projectinterface CalendarState { readonly exceptions: readonly string[];}declare class Calendar extends AggregateRoot { static rehydrate(id: string, state: CalendarState): Calendar; addException(day: string, at: Date): void; toState(): CalendarState;}declare function aCalendar(): { build(): Calendar };declare function knexCalendarRepositoryOnAFreshDatabase(): Promise<Repository<Calendar>>;
const runner = { describe, it, expect, beforeEach, afterEach };
const expectations = { createAggregate: () => aCalendar().build(), mutate: (calendar: Calendar) => calendar.addException('2026-12-25', new Date('2026-01-02T00:00:00.000Z')), idOf: (calendar: Calendar) => calendar.id, stateOf: (calendar: Calendar) => calendar.toState(),};
// the fake every handler spec usesrepositoryContract<Calendar>(runner, { ...expectations, name: 'FakeCalendarRepository', createRepository: () => new InMemoryRepository<Calendar>({ clone: (stored) => Calendar.rehydrate(stored.id, stored.toState()) }),});
// the adapter production uses, on a real databaserepositoryContract<Calendar>(runner, { ...expectations, name: 'KnexCalendarRepository', createRepository: () => knexCalendarRepositoryOnAFreshDatabase(),});If both pass the same suite, a handler tested on the fake behaves the same on the adapter for
everything the contract covers. The kit ships suites for its own ports in
@ddd-ts-kit/testing/contracts (repository, unit of work, read model store and criteria, event
bus, event store, outbox store, processed-event store, process store, job store, job scheduler,
cache, cache purger, lock, rate limiter, file storage, logger, tenant isolation) and in
@ddd-ts-kit/auth/testing (authorizer, relation tuple store), and ContractSuite, the base to
write the suite of a port of your own. Replacing an ORM or a broker is then "write the adapter,
pass the suite".
A contract covers what it tests and nothing more: behaviour specific to an adapter (the mapping of every column, a transaction rollback) gets its own integration tests.
A project generated on an ORM holds the stores of the kit as its own platform wires them:
src/platform/database/persistence.contract.spec.ts runs the outbox, processed-event, job and
process store contracts on the persistence of open-test-database.ts, with what the stack turns
on (the tenant of each event and each process instance under --tenancy, the unit of work of a
step). A store bound without what the stack asks for fails there, before it fails in production.
Builders
Section titled “Builders”Test data comes from builders, one per aggregate:
const appointment = anAppointment().forPatient('ada').startingAt(tomorrowAt9).cancelledByPatient().build();A builder extends Builder of @ddd-ts-kit/testing: valid defaults() once, a construct()
that goes through the public API of the aggregate, and one method per word of the language. The
instant of the birth is an ingredient named after its fact (bookedAt of Appointment Booked), as
generate aggregate --birth writes it; examples/scheduling keeps bornAt until its aggregates
are regenerated. Shaped like the builder of the example:
import { AggregateRoot } from '@ddd-ts-kit/kernel';import { Builder, sequence, type Defaults } from '@ddd-ts-kit/testing';
// the aggregate, from the domaindeclare class Appointment extends AggregateRoot { static create(id: string, patientId: string, startsAt: Date, bookedAt: Date): Appointment; cancel(by: 'patient' | 'practice', at: Date): void;}
interface AppointmentIngredients { readonly id: string; readonly patientId: string; readonly startsAt: Date; readonly bookedAt: Date; readonly cancelled: boolean;}
export class AppointmentBuilder extends Builder<AppointmentIngredients, Appointment> { forPatient(patientId: string): this { return this.with('patientId', patientId); }
startingAt(instant: Date): this { return this.with('startsAt', instant); }
cancelledByPatient(): this { return this.with('cancelled', true); }
protected defaults(): Defaults<AppointmentIngredients> { return { id: sequence('appointment'), patientId: 'patient-1', startsAt: new Date('2026-03-02T09:00:00.000Z'), bookedAt: new Date('2026-03-01T00:00:00.000Z'), cancelled: false, }; }
/** Through the public API only: a test can never start from a state the rules forbid. */ protected construct({ id, patientId, startsAt, bookedAt, cancelled }: AppointmentIngredients): Appointment { const appointment = Appointment.create(id, patientId, startsAt, bookedAt);
if (cancelled) { appointment.cancel('patient', bookedAt); }
return appointment; }}
export function anAppointment(): AppointmentBuilder { return new AppointmentBuilder();}- Valid defaults.
anAppointment().build()is a valid appointment. A test states only what matters to the rule it checks, so the reader sees the cause of the outcome. - Named in the ubiquitous language.
cancelledByPatient(), notwithStatus('CANCELLED'). - Built through the public API.
build()goes through the aggregate's factory and intention methods, so a test cannot start from an invalid state. If a test needs a state the public API cannot reach, either the state is impossible or the API is incomplete. - Immutable. Each call returns a new builder, so a shared base cannot leak between tests.
Rule test/builder-required. Without builders, every
change of a constructor edits fifty tests and each test buries its one relevant value under ten
irrelevant ones.
Worlds
Section titled “Worlds”Several handler specs of a context build the same test application with the same fakes. That
arrangement is written once, as a world of test/worlds/, and generated rather than copied:
npx ddd-ts-kit generate test-world schedulingThe generator reads test/fakes/*.fake.ts, finds the port each class implements in
domain/repositories/ or application/ports/, and writes
test/worlds/scheduling.world.ts: aSchedulingWorld(options) builds every fake, lets the spec
store what it starts from, then hands the fakes to the test application and returns it with
each fake under the name of its port. A spec of the example then reads:
const { application, appointmentRepository } = await aSchedulingWorld({ modules: [holders], now: NOW, given: async (fakes) => { await fakes.appointmentRepository.save(requested); },});- What it takes.
nowandidPrefixgo to the test application;modulesadds what the spec brings, its authorization module (by default no role holds a permission);fakesadds the fake of a port it cannot build alone, a reader that answers what the spec gives it;tenants, under tenancy, the tenants a per-tenant job runs for;givenreceives the fakes before the application wires them, so the events recorded while building the stored aggregates are not announced as if a command had just run. - The generated specs arrange through it. A command, a query or a job generated once
test/worlds/<context>.world.tsexists writes itsarrange()as one call of the world; generated before, or when the world lacks the fake its spec needs, it builds the test application itself, and a comment and the output of the generator say what the world would change (under a container, where the world replaces the whole arrangement). A world the generator cannot read, its buildera<Context>Worldor its options not found, is said so and never offered to--force. A fake a spec hands the world replaces the one it builds for the same port. No generator writes the world unasked. - Without an injection container (
createTestBuses), the world returns the buses and the fakes, each repository wrapped bydispatching, and the spec registers the handler it tests. - What it leaves out, and says so. A fake whose constructor needs an argument (a reader that
answers what the spec gives it), and, under a container, the fake of a port that nothing binds
or depends on yet: the test application would refuse it. Run the generator again with
--forcewhen the context gained a fake. - What stays in the spec. The permission it exercises, the data it starts from (built by the
builders) and the facts it listens to. A world holds no test data. The permission is one line,
holdersOfof@ddd-ts-kit/auth/testing: an actor holding it and an authorizer that grants it to that actor and to the system actors, refusing everybody else.
const { holder, authorizer } = holdersOf(schedulingPermissions['appointment.confirm']);const holders = authorizationModule({ authorizer });A helper written among the specs instead, test/unit/scheduling-application.ts, is reported by
test/helper-placed, a warning: test/unit/ and
test/integration/ hold specs, and a shared arrangement, test data or an in-memory port each
has its place (test/worlds/, test/builders/, test/fakes/).
Where the tests of a module live
Section titled “Where the tests of a module live”A context that divides its model into modules keeps no test/ folder at its own
level. Each module holds its tests beside its layers, <module>/test/ with unit/,
integration/, builders/ and fakes/: the specs of a part of the model are opened, moved and
reviewed with it. A builder and a fake follow their subject, not their use: the builder of an
aggregate sits in the module of that aggregate, the fake of a port or of a repository in the
module of that port, and a spec of another module imports them from there. What belongs to no
module sits in shared/test/: the worlds, which arrange a test application over the fakes of
every module, a fake or a builder named after nothing of a module (a clock), and the spec of a
guard or of several modules. generate writes each of them there, move-to-module takes the
specs of a moved file with it, and ddd-ts-kit context-layout moves a context laid out before.
A context without modules keeps its test/ folder as this page shows it.
Given / when / then
Section titled “Given / when / then”An aggregate spec is a scenario: a built state (or past events), one intention, then the recorded events or the raised error.
import { describe, expect, it } from 'vitest';import { AggregateRoot } from '@ddd-ts-kit/kernel';import { Builder, given } from '@ddd-ts-kit/testing';
// the aggregate and its builder, from the previous sampledeclare class Appointment extends AggregateRoot { readonly status: 'booked' | 'cancelled'; cancel(by: 'patient' | 'practice', at: Date): void; reschedule(startsAt: Date, at: Date): void;}declare abstract class AppointmentBuilder extends Builder<object, Appointment> { cancelledByPatient(): this;}declare function anAppointment(): AppointmentBuilder;
const at = new Date('2026-03-01T08:00:00.000Z');
describe('Appointment', () => { it('records that it was cancelled', () => { given(anAppointment()) .when((appointment) => appointment.cancel('patient', at)) .thenEvents([{ name: 'scheduling.appointment.cancelled', occurredAt: at }]) .thenState((appointment) => expect(appointment.status).toBe('cancelled')); });
it('refuses to reschedule a cancelled appointment', () => { given(anAppointment().cancelledByPatient()) .when((appointment) => appointment.reschedule(new Date('2026-03-03T09:00:00.000Z'), at)) .thenError('APPOINTMENT_ENDED'); });});given takes the builder, builds the aggregate and forgets the events recorded while
building it, so thenEvents sees only those of when. thenError takes a code, or the class
of the error and a code.
One intention per test, and assertions on events, errors and state through the public API
only. The test name states the rule: refuses to reschedule a cancelled appointment.
The four levels
Section titled “The four levels”| Level | What runs | Doubles | Speed |
|---|---|---|---|
| domain | aggregates, value objects, domain services | none at all | milliseconds |
| application | real handlers through the in-memory buses | fakes for every port, a fixed clock | milliseconds |
| adapter | one real adapter against its real dependency, plus the contract suite | none | seconds |
| end to end | the whole application with real adapters, through HTTP and the event bus | none; generated data with a fixed seed | seconds |
Normative table: section 7 of the architecture reference.
An architecture level sits beside them: ddd-ts-kit check, and a generated test that boots
each context alone to prove it stays extractable.
The same builders serve every level. End-to-end tests create their state through the public
API, use generated data with a seed printed on failure so a failing run can be replayed, and
assert what a client observes (responses, published events), never the database directly.
generate e2e names a spec after the use case whose route it drives,
test/e2e/issue-invoice.e2e.spec.ts. A spec that grows past the size limit (clean/file-size,
350 lines) is split by behaviour into parts named after it,
test/e2e/issue-invoice-refusals.e2e.spec.ts, and a journey that crosses use cases is
test/e2e/journey-<name>.e2e.spec.ts: the guard of the plugin lets these two be written by hand,
and refuses any other new end-to-end spec. What the specs of one context share (signing a
person in, a world) lives in test/e2e/support/<context>/, instead of being copied into each.
Adapter and end-to-end specs of a generated project run on PostgreSQL in process (PGlite). A
global setup (test/support/test-database-template.ts) starts it once per run and saves
its initialised cluster; each spec opens a copy of it instead of running an initdb of its own, the
slow part of starting, so that a busy machine no longer makes the hook that opens the database
outlast its timeout. Each spec still creates its tables on that copy: the code of the contexts that
creates them stays run, and measured, as before. Measured with PGlite 0.5.9 on an idle machine
(2026-10-18, five runs each): an initdb takes about 770 ms, opening a copy of the saved cluster
about 170 ms, and creating twenty tables with their keys and indexes on it about 25 ms. Saving the
tables in the copy as well would spare those 25 ms and leave the code that creates them unrun: it
is not done.
Against a server (DATABASE_URL, which the end-to-end support reads), the database the URL names
is migrated beforehand (npm run db:migrate) and each spec file runs on a database of its own,
with the tables of that one, emptied. A global setup of the end-to-end run
(test/support/test-database-setup.ts) opens the run once, where no timeout of a hook applies
(test/support/test-database-run.ts): it copies the migrated database
(create database ... template) and empties the copy. openTestDatabase(url) then copies that
template for its file (test/support/test-database-clone.ts), connects the persistence to the
copy, and drops it at close(). A file therefore waits a fraction of a second for its database
whatever the migrated one holds, the files run at the same time on a server as they do in process,
and the migrated database itself is never written. reset() still empties the tables of the copy
between two tests. Measured on PostgreSQL 18 with a migrated database of 474 MB (2026-11-12): one
copy takes 6 seconds, four at the same time 46 to 56 seconds each, more than the 30 seconds of a
hook; with the template of the run, the global setup takes 6 seconds once and each file waits 0.1
to 0.5 second. Two runs started together copy the migrated database one after the other (a lock
for the whole server, since two copies at once slow each other): the second waits for the copy of
the first, in its global setup, and their files never wait for each other. On Prisma, the client
and generated/schema.sql that each run derives first (npm run db:client, through
ddd-ts-kit prisma-client) are written by one run at a time, and the second finds them current
and writes nothing, so that of two runs started from the same sources neither reads a client the
other is rewriting. A run that watches
copies once, when it starts: a migration applied meanwhile reaches the files after a restart.
- A file starts from empty tables, but for those the project keeps. The run empties every
table of its copy except those
KEPT_TABLESlists intest/support/test-database-kept.ts, a file of the project:<schema>.<table>, or<schema>.*, written as the server stores the name and without quotes, so in lower case unless the table was created between quotes ("Countries"is listed aspublic.Countries,Countriesaspublic.countries).<schema>.*keeps every table of the schema whatever its name holds: a table whose name holds a dot or a quote has no name of its own in the list and is kept through<schema>.*only, and a schema whose name holds one cannot be listed. Any other shape (*,public, a quoted name,public.plans.v2) refuses the run with the shapes a name takes, and a name that is no table of the database (a misspelling, another case, a view) is said in one line, since it keeps nothing; the names the generated list holds for a table its tool has not created yet are not. As generated it lists what the migration tool writes of what it applied and, with an audit trail, theauditschema, which is left as the migrated database holds it (its guard refuses a truncate, and the audit package advises a trail the role of the application does not own). A migration tool told to name its table otherwise (tableNameof the knexfile,migrationsTableNameof the data source,migrations.tableofdrizzle.config.ts) has that name written there by hand. Add a table whose rows a migration inserts and the application reads: everything else a migration inserts, an application or a spec left, never reaches a spec, as on PostgreSQL in process. The tables are emptied in onetruncatewithoutcascade, each one alone (only): a kept table that references an emptied one refuses the run with both names, and is kept with the one it references; a kept table that inherits from an emptied one keeps its rows. A partition is emptied with its table: a kept partition of an emptied table refuses the run with both names, and so does a kept table that references a partition of one. A table another role owns, or one in a schema the role of the run may not use, is left with its rows and named in one line, a table of an extension is left too, the materialized views are refreshed, and a sequence no column owns keeps its value. The run names on its error output the tables it emptied that held rows, up to 20 of them, so that a row a spec misses has its cause on screen, and above 64 MB what the copy took: give the tests a database of their own, migrated and empty, to spare that time. - The connections are shared between the files that run at once. The global setup counts the
files that run at the same time, the workers of the run and no more than the files of this run
(3 files on a machine of 16 workers count 3). Under Vitest that is the list of the runner once
the filters of the command line are applied, and the share of a shard. Jest hands no list to a
global setup: the count is the spec files under
test/that the patterns of the command line match, on the path from the root of the project or on the whole path as Jest matches them, less thosetestPathIgnorePatternsignores, and the share of a shard, a number the run cannot exceed. When the count cannot be made, or finds nothing (a run that watches, a runner that lists nothing, a pattern that is no expression, notest/directory, no spec file undertest/among those of the run, which then has files this count does not see) the workers alone count. The setup then reads what the server has left (max_connections, less what it reserves and what is open, and no more than the connection limit of the role), and gives each file its share, less one connection to spare: the application under test opens a pool of that size, 10 at most (DatabaseClone.poolSize, which the four ORM hand to their connection), and the spare one is the connection that copies and drops the database, or a client a spec opens itself. A second application started in the same file, or an adapter that opens a pool of its own, is not counted. Under two connections for the pool the run is refused before any file starts, with its numbers, the number of files at once that fits (--maxWorkers) and what raises the bound that holds it (max_connections, the limit of the role, or the variable below), instead oftoo many clientsfrom the driver in the middle of a spec.TEST_DATABASE_CONNECTIONSstates a smaller number than the server leaves, for a server other runs are about to use; a value that is not a whole number, or more than the server leaves, is refused. The count is taken when the run starts: a run started later sees what the first has open, not what it will open. - A run says that it lives, twice. A database of a run is named
<database>_test_<run>_templateor<database>_test_<run>_<random>. The run holds an advisory lock keyed by its name, on a session to thepostgresdatabase of the server, from before its first database until its teardown, and every 15 seconds it writes the time of the server in the comment of its template (comment on database). The global setup of a run drops a database named after a run only when the lock of that run is free, it has not written for a minute, and nobody is connected to the database: a run that lives, in another checkout or on another machine, keeps its databases, and a database with any other name is never dropped. The lock alone would not do: a server ends sessions (a restart, a failover, a timeout of idle sessions, a laptop that slept), the run then takes another session and its lock again at once, and the comment covers that moment; the sessions on a database would not do either, since a pool that is idle has none and a template has none between two files. What a run killed a moment ago left is therefore dropped by a run that starts a minute later, not by the very next one. A run that cannot take a session again says so, and its teardown never throws: it drops what is its own on another session. A run that takes a session again and finds its template gone (it had none for more than a minute and another run dropped what it held dead, or an administrator did) says that it lost its databases, and each file that then cannot copy the template fails with the same sentence instead of thetemplate database ... does not existof the server. The copy of the migrated database has a session of its own: when the server ends that one, what is left of the copy is dropped and the copy made once more, and a second end is said as such. A statement of the run that somebody cancels (pg_cancel_backend, a job that cancels the statements that last) is no ended session: the run says that its copy was cancelled and does not take it again. The address is a direct one: behind a pooler in transaction mode a session lock means nothing, and the run needs the server itself.DATABASE_URLcannot name thepostgresdatabase, where the runs hold their sessions: the run says so. - Outside an end-to-end run (
openTestDatabase(url)called by a spec of the unit run, or a project without an HTTP stack) no global setup opened a run: the call opens one of its own, which copies and empties the migrated database itself, in the time that takes, and holds one more session, the one of its lock. Nothing counts the files that do so at the same time, each a run that sees the connections left when it starts: each opens a small pool, 4 connections at most (16 such files at once fit in the 100 connections of a server left as installed), and is refused when the server has no room for it at that moment. A refusal before any file starts, and a share of what the server leaves, are what an end-to-end run gives; outside one, bound the workers of the run yourself.
What this asks of the server:
- the role of the URL may create a database (
alter role <role> createdb) and owns the migrated one, or is a superuser, and the server is PostgreSQL 13 or later (drop database ... with (force)); - nobody else is connected to the migrated database while the run starts, because PostgreSQL
copies a database only then: an application left running on it, or a console, makes the global
setup fail after about ten seconds with a message that says so. The files never connect to it:
they copy the template of their run through the
postgresdatabase of the server; - nothing of the timeouts a role, a database or the server sets for the requests of an
application (
alter role <role> set statement_timeout = '30s'): the sessions of the run itself, the one that holds its lock and those that copy, empty and drop its databases, setstatement_timeout,lock_timeoutand, from PostgreSQL 17,transaction_timeoutto 0 for themselves, since what they do lasts as long as the database is large and a run waits its turn behind another. They open no transaction of their own, soidle_in_transaction_session_timeoutnever applies to them. The pool of the application under test is no session of the run: it keeps the timeouts of its role, as in production.
A broker or a Redis protocol server stays one for every file: with its address in the environment, the configuration of the end-to-end run keeps the files one after the other.
Under Vitest each global setup returns its teardown: one deletes the saved cluster, the other ends
the run on the server, and vitest.e2e.config.ts names both. Under Jest a setup is the default
export of its file: jest.config.js names the one that saves the cluster, jest.e2e.config.js
the one of the end-to-end run, which saves the cluster or opens the run on a server, and
test/support/test-database-teardown.ts, named by globalTeardown, deletes the cluster or ends
the run; the workers Jest starts after the setup inherit the variables it sets
(TEST_DATABASE_TEMPLATE, or TEST_DATABASE_RUN and TEST_DATABASE_POOL_SIZE on a server). A
runner loads its global setup, and what that file imports, before any import alias of the project
exists (Jest applies no moduleNameMapper there): the files directly under test/support/ import
one another by a relative path of that directory (./test-database-run), the one place where
imports/alias-only lets a relative path stand. The global setup
therefore asks nothing of what starts the runner. The spec files of a project on Jest still do:
they are ES modules, which Jest loads only when Node runs with --experimental-vm-modules. The
generated scripts pass it; a bare npx jest -c jest.e2e.config.js fails with
Must use import to load ES Module, and
NODE_OPTIONS=--experimental-vm-modules npx jest -c jest.e2e.config.js, or the runner of an
editor given that variable, starts the run as the script does. Under "importExtension": "js"
the relative path ends with the .ts of the source (./test-database-run.ts): the runner loads
the sources through its transform, which finds the file under the name it has, where a .js names
a file that does not exist and stops the run (Cannot find module), although the compiler would
accept it. imports/alias-only holds that ending, and tsconfig.json lets the type check read
it: "allowImportingTsExtensions": true, which the compiler accepts only with "noEmit": true,
both set back to false in tsconfig.build.json, so that the build emits what it emitted without
them. imports/alias-declared holds those four lines.
On the identity preset, the
integration specs under Jest took 45 CPU seconds with an initdb per spec file and 26 with the copy
(measured).
What happens after the answer (the outbox relayed, the handlers it reaches, what they store in
turn) is awaited with await application.settled(), then asserted at once. A fixed delay is slow
when long and flaky when short; settled resolves as soon as the outbox holds no pending event,
and when the time is up it fails naming what is still pending and how much of it failed.
An outside system that answers nowhere in a test run (the identity provider of the identity preset)
would keep that outbox retrying, so settled() would never end. The shared support
(test/e2e/support/start-application.ts) answers it with its fake of test/fakes/, bound in
contextsOfTheRun(): the identity preset binds FakeIdentityProviderAdmin there, and the person who
adds another outside system binds its fake in the same place.
A use case no route reaches is started by the integration event its handler receives: its
end-to-end spec (ddd-ts-kit generate e2e <context> <UseCase>, with --event <eventType> when
handlers of several events send its command) builds that event from the declaration of the
upstream, hands it to the running application with await application.publish([event]), as the
relay of the upstream would, then awaits application.settled() before asserting what a client or
another context observes.
A use case only a job starts (generate job, no route, no handler) gets the same spec with a
different start: it runs the job as the scheduler would with await application.runJob('<context>.<job>')
of the shared support, awaits application.settled(), and leaves what to observe to fill. The
generator looks for a route, then a handler that sends the command, then a job that sends it, and
names the three when it finds none. runJob fails when the job is per-tenant and the run reached no
tenant (JobRun.tenants is 0, the job was never called): open a tenant first, after reset().
A use case a background job starts (generate background-job, enqueued by another use case) is
found the same way, and its spec has three steps: the request whose use case enqueues the job,
sent through the API; const ran = await application.runDueJobs(), which runs what is due on the
queues as the worker would, until none is left, and answers the name of each job run; then
application.settled() and what a client observes. The generated spec asserts that the job is
among ran, so it fails until the request that enqueues is written. runDueJobs rejects when a
run did not succeed, naming the job, the outcome and the code of the error (The background job billing.void-invoice ended retried (UNEXPECTED_ERROR).), never its message. From its first call
the spec is the one consumer of the queues: the worker of the process, which a queue kept in
memory starts, is stopped first, so no job ends behind the spec. A job enqueued with a delay is
not due before its time: the spec of its use cases on a clock it moves is the unit spec of the
job. --job <JobName> names one job, scheduled or background, by its class or the name it runs
under, also for a use case a route reaches: its spec is written beside the one of the route, in
test/e2e/<use-case>-<job>.e2e.spec.ts.
The acceptance of a story is an end-to-end spec written before its code, from the criteria of the
story (docs/architecture/stories/<story>.md): test/acceptance/<story>.acceptance.spec.ts, one
scenario per criterion, through the API only. Each scenario runs wrapped in pending(...) of
@ddd-ts-kit/testing/e2e, which passes while an assertion fails and fails once the scenario
passes, or stops on anything else, so that a scenario waiting for its code never hides a broken
one. ddd-ts-kit acceptance <story> --lock then records a fingerprint of each criterion and each
scenario: a scenario changed while its criterion was not, or a criterion changed, is reported and
locked again only once the acceptance-judge agent, which did not make the change, let that very
version through; never silently made easier to pass. The slice that satisfies a scenario removes its wrapper; the story closes when none is
left (ddd-ts-kit acceptance <story> --gate passing).
What to test where
Section titled “What to test where”| Behaviour | Level | Why there |
|---|---|---|
| "A cancelled appointment cannot be rescheduled" | domain | an invariant: no I/O needed, exhaustive cases are cheap |
Boundaries of TimeSlot (end before start, zero length) |
domain, table-driven | value object validation |
"Cancelling publishes scheduling.appointment.cancelled once the command handler has returned; a refusal saves and publishes nothing" |
application | orchestration: load, one intention, save |
| Each declared error code of a use case | application | the contract of the handler |
"An actor without appointment.cancel is refused" |
application, with the authorization module listed | a property of the wiring of the context |
| "Only the client who booked may cancel" (the policy) | unit, on the policy alone | a pure function |
| Mapping of every column, optimistic concurrency, rollback | adapter | only the real database can say |
| The exclusion constraint that prevents double booking | adapter | the constraint lives in the database |
| Fake and adapter agree | contract, at the adapter level | keeps the application level trustworthy |
| 401 without a credential, 403 without the permission, the documented status with it | end to end | the whole chain: HTTP, authentication, bus |
| "Booking leads to a reminder being scheduled" across two contexts | end to end | crosses the event bus; eventual, so the test waits for the outcome |
| Status code and problem body for an input of the wrong shape | route spec | boundary validation |
| What a controller hands its use case, the status it answers | controller or route spec, sent through routeOf of @ddd-ts-kit/http/testing to a recording bus |
the translation of the boundary, guards included |
| "When the patient cancels, the attendance notes it" (a reaction) | reaction spec: the fact given, the command a RecordingCommandBus of @ddd-ts-kit/kernel/testing recorded asserted |
the decision of the reaction, not what the command then does |
A before-commit reaction runs inside the transaction, an after-commit one once it committed |
the suite of the kernel, once | a guarantee of the kit, never proven again by a project |
Two guidelines follow from the table. Push each rule to the lowest level that can prove it: ten cases of a cancellation window are ten millisecond tests on the aggregate, not ten HTTP round trips. And do not repeat a rule at every level: the end-to-end test proves the wiring with one case, the domain test proves the rule with all of them.
Every unit of behaviour has a spec (rule
test/spec-required), and six rules of the ESLint plugin
hold the shape of each test: its title states the rule it proves, in lower case, never should or
the name of a method (test/title-states-a-rule); it holds no if, no loop, no try
(test/no-logic); it asserts an outcome (test/assertion-present), a refusal by its code and its
facts rather than by a message (test/refusal-by-code), and never a snapshot (test/no-snapshot);
and every test runs, no .only, no .skip (test/no-only-no-skip). Arrange, act and assert stay
separated by blank lines. All six are errors: the four that read what a test says were warnings
in 0.89, so that the upgrade to them never turned a green lint red.
Properties
Section titled “Properties”A value object holds laws that hold for every value, not for the three a test names: two ranges overlap in both directions or in none, a slot is held at least until it ends, a parse then a format gives the value back. Such a law is stated once, as a property, and checked on generated values:
import fc from 'fast-check';
it('overlaps another range in both directions or in none, for any two ranges', () => { fc.assert(fc.property(anyRange(), anyRange(), (one, other) => one.overlaps(other) === other.overlaps(one)));});generate property <context> <ValueObject> starts one: a spec beside the spec of the value object
(test/unit/<name>.vo.properties.spec.ts), with the arbitrary built on its factory, a first law
(equal to the value created again from its own components) and one planned rule per kind of law.
fast-check joins the development dependencies with the first property (the generator adds it,
or npm i -D fast-check), under Vitest as under Jest; a project without a property carries no dead dependency. The title states the law, so that the page
of what the tests state reads it; fc.assert is an assertion for test/assertion-present; the
arbitrary (anyRange()) is a small helper of the spec built on the factories of the model, so that
every generated value is one the model accepts. A failing run prints the seed and the counterexample,
shrunk to the smallest. A property is for a law of the model: an invariant, a symmetry, a round trip,
an idempotence; the orchestration of a use case is stated by its scenarios, with named values, not
by a property. The spec generate value-object writes ends with a planned rule to remind of it:
keeps its invariants for any value a generator can produce, as a property. The example states four,
on its ranges and its slots.
Coverage thresholds
Section titled “Coverage thresholds”A project states the minimum coverage of each layer in one place, the coverage key of
ddd-ts-kit.config.json (CONFIG.md); the test runner reads
it, and npm run verify and the pipeline fail under it. The reference, as statements,
branches, functions, lines:
| Layer | Reference | Why this floor | Measured by |
|---|---|---|---|
domain/ |
90, 85, 90, 90 | pure code, nothing prevents testing it; it holds the rules | unit specs |
application/ |
85, 80, 85, 85 | handlers run through fakes | unit specs |
presentation/ |
80, 70, 80, 80 | mapping and status translation; its error paths are also held end to end | unit specs |
infrastructure/ |
70, 60, 70, 70 | driver failure paths are hard to provoke; adapters are held by contract suites | integration specs |
Each context is held on its own, layer by layer, from the first source file of the layer. A
freshly generated project passes: what a generator writes comes with a spec that runs it, and
the it.todo entries name the behaviour still to prove.
What a rate proves. That a line, a branch or a function ran while a test was running. A layer under its floor holds code no test has ever executed: that is certain, and it is what the gate catches.
What it does not prove. That anything was asserted about what ran, that the cases that matter were tried, or that the test would fail if the behaviour changed. A spec that calls a handler and checks nothing covers it fully. The specs named after business rules, the contract suites and the end-to-end journeys prove behaviour; coverage only says where nothing does.
A floor, not a goal. Raise a threshold when a layer has stayed above it; never write a
test to move a number. A threshold is lowered only by a recorded deviation, and the measure is
never narrowed around the code that fails it (test/coverage-governed): an uncovered branch
is tested, or deleted when nothing can reach it.
// instead of, in vitest.config.ts: a measure narrowed by hand, refused by test/coverage-governedtest: { coverage: { exclude: ['src/contexts/billing/infrastructure/**'], thresholds: { branches: 50 } } }
// write: the runner reads what it measures and its floors from ddd-ts-kit.config.jsontest: { coverage: { provider: 'v8', ...governedCoverage(mode) } } // from @ddd-ts-kit/testing/coverage"coverage": { "infrastructure": { "branches": 50 } },"deviations": [ { "what": "coverage.infrastructure.branches", "adr": "0011", "reason": "The failure branches of the driver are held by its contract suite." }]A loop that waits is a loop that skips: the specs of a context run after every change, so each spec
file is held to the time budget of its level, five seconds for a unit spec and thirty for an
integration spec by the reference (budget of ddd-ts-kit.config.json, lowered freely, raised only
by a recorded deviation). The reporter of the runner, @ddd-ts-kit/testing/budget/vitest or
@ddd-ts-kit/testing/budget/jest, names the slowest spec of each level at the end of every run and
warns when the tests and hooks of a file are over its budget, the loading of its modules left out; it fails the run once the project enforces the budget ("enforce": true under budget), when its measures are stable, since a duration depends on the load of the machine as much as on the spec. A slow unit spec hides a
world rebuilt per test instead of shared (Worlds), I/O behind what should be a fake, or a
wait; a slow integration spec rebuilds a schema per test or replays more than the behaviour it states.
The specs of the application outside the contexts, end to end, acceptance and architecture, are not
held: a flow has the time it needs; a spec of the platform counts as integration, since its adapters
open a database. On the example, the slowest unit spec takes 1.6 seconds and the slowest integration
spec 11, under load.
Mutation score
Section titled “Mutation score”A coverage rate says that a line ran under a test; a mutation score says that a test would notice
if the line changed. Every night the pipeline runs Stryker on the domain and application layers of every context
(npm run test:mutation): each mutant is one small change of the code, a condition negated, a
boundary moved, a return emptied, and the unit specs run against it; a mutant the specs notice is
detected, one they let through is a survivor. Then ddd-ts-kit mutation reads the report and holds
each layer of each context to its mutation floor of ddd-ts-kit.config.json, 80 and 75 by the
reference
(CONFIG.md).
The Stryker config writes no glob and no number: it spreads governedMutation() of
@ddd-ts-kit/testing/mutation, which mutates the domain and application layers of every context, leaves the texts
of refusals out through the ignorer of the kit, since a refusal is asserted by its code and never
by its text, every other string measured, and ignores the static mutants, those of code that runs
once when the module loads. Rule
test/mutation-governed refuses a mutate, mutator,
ignoreStatic or thresholds written by hand.
A survivor is a rule no test states. Read it as a business decision: when the behaviour is the rule, state it in a test named after it, as the trial on the example did for a withdrawn reminder planned again for the same start; when the behaviour is an accident of the code, or a branch no caller can reach, leave the mutant alive and say why, never hide it by configuration. Measured on the example on 2026-10-24 (pipeline README) with the shipped configuration: 1436 mutants, 163 of them texts of refusals and static mutants left out, 1226 killed, 41 survivors, 6 without coverage, 96.3% in 5 minutes, the lowest context at 95.4%. With the application layer, measured the same day: 2412 mutants in 283 files, 96.1% in 5 minutes 24 seconds, the application layer at 95.7% and its lowest context at 93.5%; the initial test run is what the night pays for, not the mutants.
A pull request gets a reading of its change, not the whole measure: the mutation-changed job of
the pipeline reuses the report of the last night for what the change leaves alone (the incremental
mode of Stryker, about a minute on the example when the change stays in the domain, the use cases and the specs), runs the whole measure again, about five minutes, when the change touches code the tests lean on and Stryker does not diff (a route, an adapter, a fake, a builder, a world, the platform, a dependency, the common case of a feature), then lists the survivors of the files the change touched
(ddd-ts-kit mutation --changed <base>). Read them before asking for a review; the floor stays the
business of the night.
Living documentation
Section titled “Living documentation”The business asks of tests what Gherkin promises: a reading of the rules in its own words. The kit
gives it without a second language: the title of a test states a rule (test/title-states-a-rule),
and ddd-ts-kit docs writes docs/behaviour/<context>.md from the titles of the specs of each
context, read as a specification: one heading per use case, in the words of its handler spec
(Cancel invoice (command)), holding the rules of its handler, policy, controller or route,
end-to-end spec and acceptance scenarios together; one heading per part of the model (Slot (value object), in calendars) and per reaction; the specs that fit none under their directory, headed in
words too (Not banned (guard)). Under each
heading the rules written for the project come first, then the titles a spec template of the kit
wrote, word for word (Generated by the kit), so that a reviewer reads what the project added; a
planned rule (it.todo) comes last, and it and a spec put aside are said so. A title that cites the
row of the plan it serves (#US5.02 AC1 a customer places an order) shows the row before the rule,
and the page ends with Rows of the plan, each row cited and how many titles cite it: a reviewer
checks that each rule line of the row in docs/architecture/slices.md has its title. docs/behaviour/application.md keeps the specs
outside the contexts that serve no use case (journeys, architecture). npm run docs:generate
writes them, the pre-commit hook regenerates and adds them when a spec is staged (a worker confined
to its context leaves them to the trunk), docs --check holds them current, and they are committed
with the specs: the test is the proof, the page its reading. On the example, scheduling lists 632 rules from 169 specs, 63 of its 635 titles as the kit generated them, a
table of cases counting as one rule.
A .feature file would promise the same reading, at the price of a glue of step definitions, a
second grammar to teach, and a drift the pipeline cannot see. Gherkin pays only when the business
writes the scenarios itself; then it is an input for the acceptance specs of a story, never the
runner.
Limits and when not to use it
Section titled “Limits and when not to use it”- The whole measure runs every night; a pull request gets a reading of its change. Five minutes for the domain of the four contexts of the example is too long for the loop of a change, so the job of the night holds the floor, and a pull request lists the survivors of the files it touched from a run that reuses the results of the night when the change stays in the model and the use cases, never a gate; a survivor found at night is a rule to state the next day.
- A mutation score says that a change was noticed, not that the right rule was stated. A test that kills a mutant states what the code does today: each one is read as a business decision before it is kept, and an accidental behaviour is left alive and said so rather than frozen.
- A mutation score says nothing about a rule written as a declaration. The static mutants are
ignored, those of code that runs once when the module loads: the transitions of a state machine, a
constant, a regular expression declared at the top of a file. A wrong transition in such a table
lowers no score, and the test that states the rule is its only proof;
ddd-ts-kit mutationshows the ignored mutants of each context beside its score. On the example, 90 of the 1436 mutants are static, the declaration of the appointment state machine among them. - A fake is only as good as its contract suite. Behaviour the suite does not cover can differ silently: SQL collation and ordering, constraint timing, time zone handling. When a bug comes from such a gap, add the case to the suite, not only to one adapter.
- In-process PostgreSQL is not the production server. Fast adapter specs run on PGlite; a final integration run against the real server remains necessary, and the READMEs of the ORM adapters state that MySQL and SQLite are outside the automated suite, except the Knex stores, held to their contract suites on an in-memory SQLite database in the unit run.
- The existence rules check files, not content.
test/spec-requiredandtest/builder-requiredverify that the file exists; a spec holding onlyit.todosatisfies them. The shape rules read each test, not whether the cases that matter were tried:expect(true).toBe(true)passestest/assertion-present. Leftover todos mean the work is not done:ddd-ts-kit todolists them, andstory --gate closerefuses to close a story while anit.todoof its own is left. test/no-mocksis a warning by default and concerns the tests of a context. Legacy code being adopted, or a third-party SDK with no seam, may justify a mock; make it a recorded decision rather than a habit.- End-to-end tests of eventual behaviour are slower and need care. They wait for an
outcome instead of sleeping, and a badly bounded wait makes a flaky test.
settledcounts what the outbox holds: what a broker server delivers to its consumers afterwards is awaited withcollectEvents(...).waitFor, and a projection read through the API witheventually. - No performance, load or security testing is part of this strategy, and no consumer-driven contract testing between separately deployed services: the generated OpenAPI and AsyncAPI documents with drift checks hold the contracts instead. After extracting a service, consider adding it (When to extract microservices).
Sources
Section titled “Sources”- Gerard Meszaros, xUnit Test Patterns, Addison-Wesley, 2007: Test Double and its variations (Dummy, Stub, Spy, Mock, Fake), Test Data Builder antecedents (Creation Method).
- Martin Fowler, "Mocks Aren't Stubs" (2007), "TestDouble", "TestPyramid", "ContractTest" and "GivenWhenThen", martinfowler.com.
- Steve Freeman and Nat Pryce, Growing Object-Oriented Software, Guided by Tests, Addison-Wesley, 2009: the mockist practice, "only mock types that you own", test data builders (chapter 22).
- Nat Pryce, "Test Data Builders: an alternative to the Object Mother pattern", 2007 (natpryce.com).
- Vladimir Khorikov, Unit Testing Principles, Practices, and Patterns, Manning, 2020: resistance to refactoring as a property of a good test.
- Dan North, "Introducing BDD", 2006 (dannorth.net): given / when / then.
@ddd-ts-kit/testingandpipeline/README.md.
See also
Section titled “See also”- Clean code
- Aggregates
- Ports and composition
- Delivery and idempotency
- Test runners
- Static analysis and pipeline
- Architecture reference: sections 5 and 7, rules
test/spec-required,test/no-mocks,test/builder-required