Keel by ChimpLabs
Jump to page or section Esc
Backends & Operations

Testing & Local Docker

Zero-Docker unit testing with KeelMemoryLive and local PostgreSQL 17, SurrealDB 4, and Garage S3 integration testing.

@chimp-labs/keel runs unit tests in milliseconds without Docker, and live integration tests verify the same behavior against PostgreSQL 17, SurrealDB 4.0.1, and Garage v2.1.0 S3.


Test suite layout

File Coverage Requires Docker
packages/keel/test/keel.test.ts Core tests for primitives, identical Table suite on both Memory and real node:sqlite, and push-mode Queue and Outbox No
packages/keel-workflow/test/workflow.test.ts Multi-primitive Workflow orchestration, crash and resume replay, LIFO Saga compensation, and signal timeouts on Memory and SQLite No
packages/keel/test/domain.test.ts ExternalSystem timeouts, retries, and typed boundary tests No
packages/keel/test/service.test.ts Service bounded contexts including compile-time and runtime fail-fast error contracts (ServiceUndeclaredError), .live (verifySecrets, scoped daemons, caller context), .mock, .client with makeServiceDispatcher, keel.service.<op> telemetry, and recursive inferKeelInfra No
packages/keel/test/table-reactivity.test.ts Atomic Table CDC (trackChanges: true, TableChangeTopic) and ephemeral watchTable No
packages/keel/test/error-boundary.test.ts KeelError classification exhaustiveness, classifyKeelError, reportCause, withErrorBoundary, tapErrorBoundary, and daemon onError and restartSchedule No
packages/keel/test/error-management.test.ts Typed error mapping across primitives and boundary regression checks No
packages/keel/test/observability.test.ts observeOperation, KeelMetrics, tracing spans, log annotations, snapshotKeelMetrics, and cache/daemon metrics No
packages/keel/test/config-and-memory.test.ts KeelMemoryLive, makeKeelMemoryLive, SecretStoreConfig, Dir, Chain, verifySecrets, s3ConfigFromEnv, and surrealConfigFromEnv No
packages/keel/test/resource.test.ts KeelKindSym, KeelMetaSym, is*Resource type guards, and inferKeelInfra deduplication No
packages/keel/test/plugin-protocol.test.ts Open Plugin Protocol (KeelBindSym, KeelInfraSym, KeelDefaultLayerSym, custom plugin resources in createKeel) No
packages/keel/test/edge-cases.test.ts Lock autoRenew and interruption, Idempotency collisions, competing SurrealDB 4 workers, and @ts-expect-error assertions Partial (SurrealDB cases auto-skip if down)
packages/keel/test/search-cron.test.ts Cron UTC parsing, overlap policies, and single-leader DistributedLock No
packages/keel/test/postgres.test.ts Full live KeelPostgresLive suite against Docker PostgreSQL 17 (:5439), covering LISTEN/NOTIFY topics and wildcards, ACID transaction rollback and SAVEPOINTs, FOR UPDATE SKIP LOCKED queues, push Outbox, and createKeel({ backend: "postgres" }) Auto-skips if :5439 is down
packages/keel-surreal/test/surreal.test.ts Full live KeelSurrealLive suite against Docker SurrealDB 4.0.1 (LIVE SELECT, ACID transaction rollback, sequences, DLQ, push Outbox) Auto-skips if :8000 is down
packages/keel-streams/test/durable-stream.test.ts DurableStream conformance suite (CAS, fencing, trimming, tenant isolation, TopicDurableStreamLive) across Memory, live s2-lite, and NATS JetStream Auto-skips live S2/NATS if down
packages/keel/test/s3.test.ts Full live BucketS3Live suite against Docker Garage v2.1.0 (streamed put, x-amz-meta-*, ListObjectsV2, maxBytes, live fetch() on presignPut and presignGet) Auto-skips if :3903 is down

Patterns for testing your services

1. Start with one-line KeelMemoryLive or makeKeelMemoryLive

Provide every core capability in one line in unit tests. Override only what needs custom behavior, for example RelationalStoreSqlite(), ExternalSystem.mock(...), or Service.mock(...):

import { Effect, Layer } from "effect"
import { makeKeelMemoryLive } from "@chimp-labs/keel"

const TestLayer = Layer.mergeAll(
  makeKeelMemoryLive({
    secrets: { STRIPE_API_KEY: "sk_test_123" },
    flags: { "new-checkout": true },
  }),
  PaymentsSystem.mock({
    charge: ({ amountCents }) =>
      Effect.succeed({ chargeId: "ch_test_1", amountCents }),
  }),
)

2. Isolate bounded contexts with Service.mock and in-memory dispatchers

When testing a downstream service like BillingService without booting InventoryService’s tables or daemons, use InventoryService.mock(handlers). Unlike ad-hoc stubs, .mock(...) validates input and output Schema definitions, enforces declared errors by escalating undeclared errors to ServiceUndeclaredError defects, and emits keel.service.<op> telemetry:

import { Effect, Layer } from "effect"
import { makeServiceDispatcher } from "@chimp-labs/keel"

// Unit-test a caller with a contract-checked mock (zero infra)
const InventoryMock = InventoryService.mock({
  reserve: ({ sku }) => Effect.succeed({ reservationId: `res_${sku}` }),
  getStock: () => Effect.succeed({ available: 42 }),
})

// Or test full wire serialization & resilience with zero sockets via `makeServiceDispatcher`
const dispatch = makeServiceDispatcher(InventoryService)
const InventoryOverWire = InventoryService.client((req) =>
  dispatch({ operation: req.operation, input: req.input }),
).pipe(Layer.provide(InventoryLive))

See examples/advanced/07-bounded-context-service.ts for a complete runnable zero-Docker modular-monolith and remote-client example.

3. Test Effect.Config loaders and secret chains deterministically

Use ConfigProvider.fromEnv and ConfigProvider.layer to test SecretStoreConfig, BucketS3ConfigLive, KeelPostgresConfigLive, and KeelSurrealConfigLive without mutating process.env:

import { ConfigProvider, Effect } from "effect"
import { getSecret, SecretStoreConfig } from "@chimp-labs/keel"

const provider = ConfigProvider.fromEnv({ STRIPE_API_KEY: "sk_test_cfg" })
const secret = await Effect.runPromise(
  getSecret(StripeKey).pipe(
    Effect.provide(SecretStoreConfig),
    Effect.provide(ConfigProvider.layer(provider)),
  ),
)

4. Assert observability in tests

Inspect snapshotKeelMetrics to verify operation, error, cache, and daemon counters, including keel.service.<op> telemetry from Service calls.

5. Isolate live PostgreSQL 17 and SurrealDB 4 integration tests

Start the local Docker backing stack (PostgreSQL 17 on :5439, SurrealDB 4.0.1 on :8000, and Garage v2.1.0 on :3900 and :3903) with pnpm infra:up or docker compose up -d postgres.

PostgreSQL 17 (KeelPostgresLive). As in test/postgres.test.ts, isolate each test in its own temporary database or dedicated schema so concurrent tests do not collide on tables, LISTEN/NOTIFY channels, or event sequences, and drop it in finally:

import { randomUUID } from "node:crypto"
import { Client as PgClient } from "pg"
import { KeelPostgresLive } from "@chimp-labs/keel-postgres"

const adminUrl =
  process.env.KEEL_POSTGRES_URL ?? "postgresql://keel:[email protected]:5439/keel"

const dbName = `keel_t_${randomUUID().replace(/-/g, "").slice(0, 8)}`
const admin = new PgClient({ connectionString: adminUrl })
await admin.connect()
await admin.query(`CREATE DATABASE "${dbName}"`)
await admin.end()

const testUrl = new URL(adminUrl)
testUrl.pathname = `/${dbName}`

const layer = KeelPostgresLive({ url: testUrl.toString() })
// Run your Effect test with `Effect.provide(layer)`, then terminate backends & `DROP DATABASE IF EXISTS "${dbName}"` in `finally`.

SurrealDB 4 (KeelSurrealLive). Each test generates a random database name inside keel_test, so tests run concurrently with zero cross-test interference:

const layer = KeelSurrealLive({
  url: process.env.SURREAL_URL ?? "ws://127.0.0.1:8000",
  namespace: "keel_test",
  database: `db_${crypto.randomUUID().replace(/-/g, "").slice(0, 8)}`,
  username: "root",
  password: "root",
  autoCreate: true,
})

6. Verify compile-time contracts with @ts-expect-error

Keep a type-assertion block checked by pnpm typecheck (tsc --noEmit) so refactors never weaken wildcard matching, branded-ID joins, $inc numeric checks, Bucket prefix constraints, or Service closed handler error contracts. See test/edge-cases.test.ts and test/service.test.ts for examples.

7. Re-rendering architecture diagrams

Diagram sources live in /assets/src/*.mmd. After editing any .mmd file, regenerate the PNGs:

pnpm docs:diagrams

8. CI verification

.github/workflows/ci.yml starts PostgreSQL 17 (:5439), SurrealDB 4.0.1 (:8000), and Garage v2.1.0 (:3900 and :3903) via docker compose, bootstraps Garage with node docker/init-garage.mjs, and runs:

pnpm typecheck
pnpm build
pnpm test
pnpm demo
pnpm examples:basic
pnpm examples:advanced