Files
TREK/server/tests/helpers/factories/context.ts
T
Maurice 1bba65634c test(server): seed and read test data through ORM factories
The server suite seeds and reads its database through some 5,500 raw
better-sqlite3 statements on the sync handle. They restate the schema by
hand, skip the repositories the app goes through and run on SQLite only,
so nothing in the suite could ever exercise the dialect layer on another
engine.

tests/helpers/factories/ adds typed factories per domain (users, trips and
days, places, assignments, bookings, budget, packing, to-dos, files,
journeys, tours, collections, notifications, settings, plugins, tokens,
atlas, vacay, photos, collab) and generic readers (findRow, findRows,
countRows, updateRows, deleteRows) that go through MikroORM in a request
context of their own, against the app's ORM or a createTestOrm handle.
They refuse a write to a read-only foreign-key twin, which MikroORM would
otherwise drop without a word. The README there is the conversion guide.

The categories integration suite and the tags and calendar-feed e2e suites
are converted in full as worked examples; the tags suite also moves from
hand-rolled tables to the migrated snapshot.

lint:test-sql (scripts/test-sql-ratchet.mjs) holds the raw statements left
to a per-file baseline: growth and stale entries fail, files whose subject
is raw SQL are exempt with a reason, and a single statement can be allowed
with a test-sql-allow comment. CI runs it next to lint:boundaries.
2026-10-08 18:44:39 +02:00

38 lines
1.4 KiB
TypeScript

import type { EntityManager } from '@mikro-orm/core';
import { withRequestContext } from '../../../src/nest/database/request-context';
/**
* Anything carrying the ORM's global EntityManager: `app.get(MikroORM)` in a
* `buildApp()` suite, the `TestOrm` from `createTestOrm(db)` in a unit or
* partial-module suite, or a `MikroORM` a test built itself.
*/
export interface FactoryOrm {
em: EntityManager;
}
/**
* Runs one factory step in a request context of its own, the way production
* runs an MCP call or a cron tick (`withRequestContext`).
*
* The app's ORM keeps `allowGlobalContext: false`, so a write outside a
* context would be refused; and a fresh fork per step means no identity map
* survives into the next step, where `resetTestDb()` may already have deleted
* the rows it remembers. Inside the context `orm.em` resolves to that fork.
*/
export function inContext<T>(orm: FactoryOrm, fn: (em: EntityManager) => Promise<T>): Promise<T> {
return withRequestContext(orm, () => fn(orm.em));
}
const sequences = new Map<string, number>();
/**
* The next number for a named default (`user3@test.example.com`). Per worker
* process, never reset: like the legacy factories, names stay unique across
* the tests of one file even when `resetTestDb()` runs between them.
*/
export function nextSeq(name: string): number {
const n = (sequences.get(name) ?? 0) + 1;
sequences.set(name, n);
return n;
}