Tooling & production/Testing with Testkit
Testing with Testkit
In-memory SQLite templates, Postgres test databases, HTTP and Live session harnesses, fake clocks, and provider contract suites.
On this page
The github.com/fletchhq/fletch/testkit package provides deterministic harnesses for testing HTTP handlers, Live components, SQLite and Postgres repositories, background jobs, mailers, and custom subsystem adapters without slow setup or flaky clocks.
Creating a Test Harness
Use testkit.New(t, opts...) for standalone route and component tests, or testkit.NewFor(t, buildFn, opts...) when constructing your real application from bootstrap/app.go with injected test dependencies (testkit.Deps). Both return a *testkit.TK scoped to t with automatic cleanup.
The build function has the signature func(testkit.Deps) (*fletch.App, error). Pass deps.Options() to your app constructor so the fakes are wired in. The scaffolded tests/app_test.go builds the real app this way:
func TestInvoiceFlow(t *testing.T) {
tk := testkit.NewFor(t, func(d testkit.Deps) (*fletch.App, error) {
cfg := config.Config{Env: "test"}
cfg.Database = config.DatabaseConfig{URL: ":memory:", AutoMigrate: true, MigrationsDir: "../database/migrations"}
return bootstrap.New(cfg, d.Options()...)
},
testkit.WithClockStart(time.Date(2026, 12, 1, 9, 0, 0, 0, time.UTC)),
)
_ = tk
}
With AutoMigrate, migrations run in an OnStart hook, so start the app with tk.App.Start(ctx) before sending requests, as the scaffolded test’s start helper does. A module test can skip bootstrap and mount just its module: app := fletch.New(d.Options()...); return app, app.Mount(m).
| Option | Purpose |
|---|---|
testkit.WithClockStart(t) |
Seed the harness fake clock at a fixed starting timestamp. |
testkit.WithMigrations(fsys) |
Apply SQL migrations from an fs.FS to the test database. |
testkit.WithTemplate(tmpl) |
Clone a pre-migrated SQLite template instead of re-running migrations. |
testkit.WithRoutes(fn) |
Register inline test routes on the harness app. |
testkit.WithAppOptions(opts...) |
Forward extra fletch.Option values to the underlying fletch.App. |
Fast SQLite Template Cloning
Running full SQL migrations inside every subtest adds up quickly on larger schemas. Call testkit.NewTemplate(ctx, migrations) once in TestMain to apply your migrations to an in-memory SQLite template, then pass that template into each test with testkit.WithTemplate(tmpl). Each test then gets a clean, isolated in-memory copy of the migrated image. Restoring that image is much cheaper than replaying migrations, though its cost still grows with the size of the schema and any rows the template holds.
NewTemplate returns a *sqlite.Template from github.com/fletchhq/fletch/data/sqlite:
var dbTemplate *sqlite.Template
func TestMain(m *testing.M) {
var err error
dbTemplate, err = testkit.NewTemplate(context.Background(), os.DirFS("../database/migrations"))
if err != nil {
panic(err)
}
os.Exit(m.Run())
}
func TestOrders(t *testing.T) {
tk := testkit.New(t, testkit.WithTemplate(dbTemplate))
_ = tk
}
Isolated Postgres Tests
When you need to test Postgres-specific SQL, advisory locks, partial indexes, or quiver/postgres queries against a real database server, use testkit.Postgres:
func TestPostgresLedger(t *testing.T) {
db := testkit.Postgres(t, testkit.WithPostgresMigrations(migrations.FS))
// db is an isolated *sql.DB torn down automatically via t.Cleanup.
_ = db
}
testkit.Postgres provisions an isolated database per test, runs the provided migrations through testkit.WithPostgresMigrations(fsys), and cleans it up when t finishes.
HTTP Requests, Uploads, and In-Memory Servers
Execute HTTP requests directly against any http.Handler with testkit.Do(t, handler, req). It returns a *testkit.Response carrying the status code, headers, raw body, and assertion helpers for HTML and JSON responses:
req := httptest.NewRequest(http.MethodGet, "/api/orders", nil)
res := testkit.Do(t, handler, req)
_ = res
For multipart file upload endpoints, construct upload parts with testkit.FilePart to test file validation, content types, and storage persistence without writing temporary files on disk.
When tests require a running HTTP transport or multi-request cookie/navigation flows, testkit.MemServer runs the handler in memory and testkit.Browser drives browser-level integration flows against it.
Testing Live Components Without a Browser
testkit.OpenLive mounts a Live component over an in-process transport and returns a *testkit.LiveSession without launching headless Chrome:
sess := testkit.OpenLive(
t,
handler,
"/orders/42",
testkit.WithHeader("Cookie", authCookie),
)
_ = sess
Through *testkit.LiveSession, you can dispatch Live events as a user would, inspect the rendered DOM Diff returned for each event, check state transitions against Expectation, and assert specific LiveError codes when authorization or validation rejects an action.
Deterministic Clocks, Background Jobs, and Mail
Flaky tests usually come from wall-clock time, async workers, or real network calls. testkit keeps all three deterministic:
- Fake clocks: Create a controllable clock with
testkit.NewClock(start)and inject it into your app viafletch.WithClock(or passtestkit.WithClockStarttotestkit.New). Advance time directly to test session expiry, token lifetimes, rate limits, and scheduled jobs. - Synchronous job draining: Use
testkit.Jobsto run queued Quiver jobs synchronously inside a test so assertions can verify side effects without polling or sleeps. - Captured email inspection: Wire
mail.Outbox()as your test mailer to record every outbound message in memory and assert recipients, subjects, rendered HTML/plain bodies, headers, and attachments.
Provider Contract Test Suites
If you build a custom adapter for mail, caching, authentication sessions, background jobs, PubSub, or object storage, run the matching Fletch contract suite from your adapter’s *_test.go file to verify behavioral parity with built-in drivers:
| Subsystem | Contract package / entry point |
|---|---|
github.com/fletchhq/fletch/mail/mailtest (mailtest.Run) |
|
| Cache | github.com/fletchhq/fletch/cache/cachetest (cachetest.Run) |
| Auth sessions | github.com/fletchhq/fletch/auth/authtest (authtest.RunSessions) |
| Jobs | github.com/fletchhq/fletch/quiver/quivertest |
| PubSub | github.com/fletchhq/fletch/pubsub/pubsubtest |
| Storage | github.com/fletchhq/fletch/storage/storagetest |
func TestCustomCacheContract(t *testing.T) {
cachetest.Run(t, func(t *testing.T) cache.Store {
return newMyCustomCache(t)
})
}