--- title: "Testing" description: "Test Beignet apps at the use-case, route, contract, provider, seed, and resource boundaries." url: "https://www.beignetjs.com/testing" markdown_url: "https://www.beignetjs.com/markdown/testing.md" framework_version: "0.0.65" documentation_scope: "current-checkout" source_revision: "e5b4771b262efbdd036e3a40a514c08d1508316c" source_modified: true --- # Testing For a walkthrough with runnable tests, follow [Test a feature from business rule to HTTP](https://www.beignetjs.com/markdown/guides/test-a-feature.md). It exercises the starter's Todos use cases, HTTP routes, and SQLite adapter. Beignet apps should test the boundary that owns the behavior. There are four test idioms, one per situation: | Situation | Idiom | | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | | Business rules in a use case | `createTestPorts(...)` + `createTestContextFactory(...)` + `createUseCaseTester(...)` | | Contract request and response over HTTP | `createTestApp(...)` with the app's shared `appContext` blueprint | | Workflow artifacts: jobs, listeners, schedules, notifications, tasks, uploads | `createTestContext(...)` fixture with `dispose()` | | Repository and persistence behavior | `createDatabaseTestHarness(...)` against a real test database | Test placement follows the same ownership rule: feature behavior tests live in `features//tests/`, while infra and server modules may keep adjacent `*.test.ts` files beside the module they exercise. Generated features and resources include starter tests for the generated behavior; see [CLI](https://www.beignetjs.com/markdown/cli.md) for what each generator scaffolds. Build application fixtures with the exported `@beignet/core/testing` helpers and keep shared feature factories in `features//tests/factories/`. Beignet's internal regression-test fixtures are not included in the published core package. The generated starter ships `lib/beignet-test.ts`, a small wrapper around Node's test runner and assertions. Import test helpers from that file so the same tests run through the generated `test` package script with npm, pnpm, yarn, or Bun. The script starts `lib/beignet-test-runner.ts` with `node --import tsx`, which ensures Node remains the test runtime even when Bun starts the package script. The runner discovers app test files and passes them explicitly to Node's test runner. Discovery honors path overrides from `beignet.config.ts`, `.json`, `.mjs`, or `.js`. Run `beignet doctor --fix` to upgrade an older generated test script; custom test commands are left alone. ## Use case tests Use case tests are the default for business behavior because they avoid HTTP setup and run against app-owned ports. A minimal test builds a port fixture, a context factory, and a tester, then runs the use case: ```typescript import { expect, test } from "@/lib/beignet-test"; import { createUseCaseTester } from "@beignet/core/application"; import { createTestUserActor } from "@beignet/core/testing"; import { createTestContextFactory, createTestPorts } from "@beignet/core/testing"; import type { AppContext } from "@/app-context"; import { createProjectUseCase } from "@/features/projects/use-cases"; import { initialPorts } from "@/infra/port-wiring"; import { createInMemoryProjectRepository } from "@/infra/projects/in-memory-project-repository"; test("creates a project", async () => { const fixture = createTestPorts({ base: initialPorts, overrides: { gate: initialPorts.gate, projects: createInMemoryProjectRepository() }, }); const createContext = createTestContextFactory({ ports: fixture.ports, actor: createTestUserActor("user_test"), }); const tester = createUseCaseTester(createContext); const project = await tester.run(createProjectUseCase, { name: "Roadmap" }); expect(project.name).toBe("Roadmap"); }); ``` Port overrides are typed partials: a test declares only the port surface it exercises, and any missing member throws a named error on use. The context factory also accepts `auth` and a `tenant` built with `createTestTenant(...)`, and it attaches a live `ctx.gate` automatically when `ports.gate` exposes `bind(...)`, so authorization runs against the final test identity. Use `createTestImpersonatedUserActor(...)` when an admin acting as another user must appear in audit metadata. `createTestPorts(...)` also supplies a recording `bestEffortWork` port. Deferred callbacks remain in `fixture.pendingBestEffortWork` until the test calls `await fixture.flushBestEffortWork()`. A flush runs one FIFO snapshot, so work deferred by a running callback remains pending for the next explicit flush. It attempts the complete snapshot before rejecting with any callback failures. When the behavior under test runs inside `ctx.ports.uow.run(...)`, add the app's production transaction wiring to the same fixture and turn on `transaction.outbox` so events recorded inside the transaction commit atomically with the data: ```typescript import { assertOutboxPending } from "@beignet/core/testing"; import { createDomainEventRecorder } from "@beignet/core/ports"; import { createTransactionPorts } from "@/infra/db/transaction-ports"; import type { AppTransactionPorts } from "@/ports"; const projects = createInMemoryProjectRepository(); const fixture = createTestPorts({ base: initialPorts, overrides: { gate: initialPorts.gate, projects }, transaction: { outbox: true, ports: (ports) => createTransactionPorts({ audit: ports.audit, repositories: { projects }, idempotency: ports.idempotency, outbox: ports.outbox, events: createDomainEventRecorder(), }), }, }); // ...run the use case as above, then: assertOutboxPending(fixture.outbox, { kind: "event", name: "projects.created" }); ``` `infra/db/transaction-ports.ts` is a pure module that assembles the app's transaction-scoped ports, so production providers and tests share one definition of what runs inside a transaction. Keep vendor SDK mocks out of these tests; mock or implement the app-owned port instead. ## Route tests Use route tests when the behavior belongs to HTTP: request parsing, contract validation, response validation, hooks, auth, rate limits, and error ownership. Route tests reuse the app's real context blueprint. `server/context.ts` declares the blueprint once with `defineServerContext(...)`, `server/index.ts` passes it to the production server, and route tests pass the same value to `createTestApp(...)`: ```typescript import { expect, it } from "@/lib/beignet-test"; import { createTestPorts } from "@beignet/core/testing"; import { defineRoutes } from "@beignet/core/server"; import { createTestApp } from "@beignet/web/testing"; import type { AppContext } from "@/app-context"; import { createProject } from "@/features/projects/contracts"; import { projectRoutes } from "@/features/projects/routes"; import { initialPorts } from "@/infra/port-wiring"; import { createInMemoryProjectRepository } from "@/infra/projects/in-memory-project-repository"; import { appContext } from "@/server/context"; it("creates a project through the contract", async () => { const fixture = createTestPorts({ base: initialPorts, overrides: { auth: { getSession: async () => ({ user: { id: "user_test" } }) }, gate: initialPorts.gate, projects: createInMemoryProjectRepository(), }, }); const app = await createTestApp({ ports: fixture.ports, context: appContext, routes: defineRoutes([projectRoutes]), }); const project = await app.request(createProject, { body: { name: "Roadmap" } }); await app.stop(); expect(project.name).toBe("Roadmap"); }); ``` `createTestApp(...)` runs `@beignet/web` under the hood. Two defaults differ from production servers, and an explicit option always wins: `onUnboundPorts` defaults to `"ignore"` so apps with deferred provider ports still boot, and `mapUnhandledError` surfaces `err.message` in the 500 body so failing tests show the real error. Contract metadata such as `rateLimit` and `idempotency` is only enforced when the matching hook is in the test app's `hooks` and its port is bound — pass the same `createRateLimitHooks(...)` / `createIdempotencyHooks(...)` the server configures to assert real 429s and idempotency replays. `createTestPorts(...)` already binds memory `rateLimit` and `idempotency` ports, and `createTestApp(...)` warns at creation when registered contracts declare behavior the test app cannot enforce. Because the test runs the real blueprint, identity comes from the same place it does in production: override the `auth` port to simulate a signed-in session. Use `createTestRequester(...)` from `@beignet/web/testing` to apply shared headers such as a tenant header, and `app.safeRequest(...)` when the test expects an HTTP error as a typed result instead of a thrown `ContractError`. Cover both successful responses and declared business errors. The underlying `app.server` preserves the blueprint's service-input type, so non-HTTP tests can call `app.server.runServiceContext(input?, fn)` without assembling context manually. ### Testing Next route files The `@beignet/next` webhook, payment webhook, schedule, and outbox drain route factories build app context from the incoming request through `server.createRequestContext(...)`, not from `next/headers`, so route modules run under the generated `test` script with a plain `Request`: ```typescript // app/api/webhooks/github/route.test.ts import { expect, it } from "@/lib/beignet-test"; import { POST } from "./route"; it("rejects unsigned webhook deliveries", async () => { const response = await POST( new Request("http://localhost/api/webhooks/github", { method: "POST", body: JSON.stringify({ action: "opened" }), }), ); expect(response.status).toBe(400); }); ``` To drive a route factory against controlled context, pass a fake `server` exposing `createRequestContext` — the option accepts a `NextServer`, a core `ServerInstance`, or any test fake with that method. See the [`@beignet/next` README](https://www.npmjs.com/package/@beignet/next) for a full schedule-route example. ## Workflow artifact tests Jobs, listeners, schedules, notifications, tasks, and uploads run with a service identity instead of an HTTP request. Test them with the one-call `createTestContext(...)` fixture: it builds memory ports, assembles an app context with actor, tenant, request ID, trace ID, and a live bound gate, and enters the ambient request context so enrichment matches production. Dispose the fixture after each test: ```typescript import { afterEach, expect, it } from "@/lib/beignet-test"; import { createTestSystemActor } from "@beignet/core/testing"; import { createTestContext } from "@beignet/core/testing"; import type { AppContext } from "@/app-context"; import { LogProjectArchivedJob } from "@/features/projects/jobs"; const makeContext = createTestContext(); let fixture: ReturnType; afterEach(() => fixture.dispose()); it("audits handled archive jobs", async () => { fixture = makeContext({ actor: createTestSystemActor("test-worker") }); await LogProjectArchivedJob.handle({ job: LogProjectArchivedJob, payload: { projectId: "project_1" }, ctx: fixture.ctx, }); expect(fixture.audit.entries).toMatchObject([ { action: "jobs.projects.log-archived" }, ]); }); ``` The fixture supports `using fixture = makeContext(...)` for explicit resource management, and `ports` accepts the same typed partial overrides as `createTestPorts(...)`. Operational tasks follow the same idiom: build a fixture with `createTestServiceActor(...)` and pass `fixture.ctx` to `runTask(...)` from `@beignet/core/tasks`. Production context creation belongs to the CLI runner via `server/tasks.ts`, not to task tests. ## Repository and persistence tests Repository tests prove that a concrete adapter implements its port contract against a real database. Keep them adjacent to the infra they exercise, and use `createDatabaseTestHarness(...)` with the generated `infra/db/test-database.ts` helper to keep setup, seeding, factory resets, and cleanup in one place: ```typescript import { createDatabaseTestHarness } from "@beignet/core/testing"; const databaseHarness = createDatabaseTestHarness({ create: createTestDatabase, ctx: (database) => ({ ports: database.ports }), reset: (database) => database.reset(), close: (database) => database.close(), factories: [postFactory], seeds: [demoPostsSeed], }); afterEach(async () => { await databaseHarness.cleanup(); }); const { ctx } = await databaseHarness.setup({ seed: true }); const post = await postFactory.create(ctx, { title: "Database conventions", }); ``` ### Factories and seeds Use `@beignet/core/testing` when tests need realistic records or repeatable demo data. Factories should build app-owned data and persist through ports, not through ORM tables or provider SDKs: ```typescript // features/posts/tests/factories/post.ts import { createFactory } from "@beignet/core/testing"; import type { AppContext } from "@/app-context"; export const postFactory = createFactory("posts.post", { defaults: ({ sequence }) => ({ title: `Post ${sequence}`, content: "Created by a Beignet test factory.", }), persist: (ctx: AppContext, post) => ctx.ports.posts.create(post), }); ``` Seeds wrap factories for repeatable demo data: declare them with `defineSeed(...)`, run them with `runSeeds(...)`, and reset factory sequences between tests with `resetFactories(...)`. Generate starter files with `beignet make factory posts.post` and `beignet make seed posts.demo-posts`; keep factories under `features//tests/factories/` and seeds under `features//seeds/`. Use `beignet db seed` for app-level demo data once the app defines a `db:seed` script and a `server/seed.ts` entrypoint. For `framework: "web"`, generated `server/seed.ts` calls `createAppServer()`, runs the feature seeds through `server.runServiceContext(...)` with a `beignet-seed` service actor, and stops the server in `finally`. The scoped callback keeps ambient request correlation from escaping into the rest of a one-off script. The service context must accept an `actor` input; the generator checks the installed app types before writing a new entrypoint. ## Assertion helpers `@beignet/core/testing` ships assertion helpers that work against Beignet ports and memory adapters without importing concrete infra. Each `assertX(...)` has a matching `findX(...)`, and most have an `assertNoX(...)` negation. See the [generated API reference](https://www.beignetjs.com/markdown/api-reference.md) for exact signatures. | Helper | What it asserts | | ----------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | | `assertRecordedEvent` | Events captured by `createRecordingEventBus(...)` | | `assertDispatchedJob` | Jobs captured by `createRecordingJobDispatcher(...)` | | `assertScheduleRun` | Run intent captured by `createRecordingScheduleRunner(...)` | | `assertMailDelivery` | Deliveries on a memory mail port | | `assertNotificationDelivery` | Deliveries on a memory notification port | | `assertStorageObject` | Object content and metadata behind a storage port | | `assertAuditEntry` | Entries in a memory audit log | | `assertIdempotencyCompleted` / `assertIdempotencyInProgress` | Idempotency entry state | | `assertOutboxPending` / `assertOutboxDelivered` / `assertOutboxRetryScheduled` / `assertOutboxDeadLettered` | Outbox message state | | `assertOutboxDrainResult` | Delivery, dead-letter, lease, and settlement counters from `drainOutbox(...)` | | `assertProviderInstrumentationEvent` | Events captured by `createRecordingProviderInstrumentation(...)` | The recording helpers pair a port implementation with its captured log. Wire the port through the context factory rather than spreading an existing context, because spread copies drop the live `ctx.gate`: ```typescript import { assertRecordedEvent, createRecordingEventBus } from "@beignet/core/testing"; const { bus, events } = createRecordingEventBus(); const ctx = createContext({ ports: { ...fixture.ports, eventBus: bus } }); await publishPostUseCase.run({ ctx, input }); assertRecordedEvent(events, { name: "posts.published", payload: { postId: "post_1" } }); ``` `createRecordingEventBus()` applies the same canonical JSON and transport-stability checks as Beignet's runtime event buses. A test therefore cannot record an event payload that Redis or the outbox would reject. Await `bus.publish(...)` before reading the captured `events` log. Outbox assertions read a memory outbox or a message snapshot, so tests check durable workflow state without widening the production `OutboxPort` read API: ```typescript import { assertOutboxDelivered, assertOutboxDrainResult } from "@beignet/core/testing"; import { drainOutbox } from "@beignet/core/outbox"; const result = await drainOutbox({ outbox, registry, eventBus, jobs }); assertOutboxDrainResult(result, { claimed: 1, delivered: 1, settlementFailed: 0, leaseLost: 0, }); assertOutboxDelivered(outbox.messages, { kind: "event", name: "posts.published" }); ``` Use `createRecordingScheduleRunner(...)` to verify schedule run intent without executing the handler, and `createInlineScheduleRunner` from `@beignet/core/schedules` when the handler itself is under test. For stateful workflows, add at least one test that follows the durable chain from transition use case through outbox, listener, job dispatch, retry, and dead-letter behavior; see [Workflows](https://www.beignetjs.com/markdown/workflows.md). ## Generated resource checks After generating or editing a resource, run: ```bash bun beignet check ``` It runs every check in one pass: `test` covers behavior, `lint` (Biome) covers code style, `typecheck` catches contract/type drift, `beignet lint` checks dependency direction, and `beignet doctor --strict` checks app wiring that TypeScript cannot fully prove, such as route files that no longer match registered contracts, missing canonical client helpers, and local `AppContext` redeclarations. ## Provider tests Provider tests stay close to the adapter and verify the provider implements its port contract, including startup, teardown, retries, and error translation. Use `installProviderForTest(...)` from `@beignet/core/testing` to run provider setup against test ports; it returns the merged ports, the raw setup result, and `start`/`stop` runners for the lifecycle hooks: ```ts import { installProviderForTest } from "@beignet/core/testing"; import type { CachePort } from "@beignet/core/ports"; const installed = await installProviderForTest(createRedisCacheProvider(), { ports: { devtools }, config: { URL: "redis://localhost:6379" }, }); const cache = installed.ports.cache as CachePort; await cache.set("posts:list", "[]"); await installed.stop(); ``` `config` is passed to provider setup as-is, matching server startup. Pass `createServiceContext` when the provider under test builds service contexts from runtime entrypoints. Application tests should not depend on live providers unless the test is explicitly an integration test. ## Runtime performance The Beignet repository includes an informational runtime benchmark suite. From a repository checkout, run `bun install --frozen-lockfile` followed by `bun run bench:runtime`. It compares built Beignet Fetch handlers with minimal native handlers on Node and Bun, covering GET, validated POST, authentication hooks, instrumentation, and small and large route registries. Separate POST cases measure local authentication and request event recording independently, then together. Authentication uses a synthetic session and the instrumentation sink counts events without storing them or performing external I/O. Use `bun run bench:runtime -- --suite routing` to measure dynamic and mixed registries, static-versus-parameter precedence, HEAD dispatch, and 404/405 responses. Static and dynamic requests in mixed registries are measured separately. `--suite all` runs both suites. Both runtimes execute an isolated fixture of compiled JavaScript with the same Beignet exports; fixture preparation is excluded from timing. Reports include throughput, median/p95 request latency, startup phases, and memory snapshots. These are sequential in-process measurements, not production HTTP capacity or a Next.js/serverless cold-start guarantee. Measure your own application with realistic providers and concurrent network traffic before using the results for capacity planning. See the [benchmark methodology and options](https://github.com/taylorbryant/beignet/tree/main/benchmarks/runtime) for reproducible runs and limitations. CI checks workload correctness; full benchmark reports are informational and do not impose timing thresholds.