Part 12 of a series that builds one backend server on Node with Effect 4. The code is in devtrillo/effect-on-the-backend, and this part is the
part-12tag.
Part 11 ended with a table of curl results: 401 without a token, 201 with one, 401 before 400 on a bad body. I typed every one of those requests myself. Postgres had to be running, and so did the server. This part turns that table into tests that don’t need either.
The plan: keep the handlers and both middleware layers exactly as main.ts runs them, and swap only the services underneath. Users runs in memory, Tokens becomes a fake, and an in-process client calls the handlers without a socket.
Two packages, pinned
npm install -D -E @effect/vitest@4.0.5 vitest@5.0.5@effect/vitest still lives outside effect, as part 1 said it would, and its 4.0.5 peers on effect ^4.0.5 and vitest >=5.0.0 <6.0.0. npm test is vitest run. Vitest reads the .ts imports without a config file, and tsconfig.json now includes test/ so npm run check type-checks the tests too.
Getting the handlers out of main.ts
A test can’t import main.ts: its last line launches the server. So ValidationLive, AuthorizationLive and the group move to src/Http.ts, and the group stops providing anything:
// The handlers with nothing provided. They need Users, and the two middleware layers above.export const UsersHttp = HttpApiBuilder.group( Api, "users", Effect.fn(function* (handlers) { const users = yield* Users return handlers .handle("get", ({ params }) => users.find(params.id)) .handle("create", ({ payload }) => users.create(payload)) }),)AuthorizationLive also loses its Layer.provide(Tokens.layer). main.ts does the providing now, with the Postgres versions:
// The handlers, their middleware, and the Postgres services behind both.const UsersLive = UsersHttp.pipe( Layer.provide([ValidationLive, AuthorizationLive]), Layer.provide([Users.layer, Tokens.layer]),)main.ts drops to 34 non-blank lines (part 11: 61). Same curl results as part 11, which I checked once more by hand, against a fresh Postgres 18, for the last time.
The test layer
const ada = { id: "1", name: "Ada", email: "ada@example.com" }
// One valid token, for Ada. No hashing and no table: this fake stands in for Postgres.const TokensTest = Layer.succeed( Tokens, Tokens.of({ issue: () => Effect.die("not used in tests"), verify: (token) => Redacted.value(token) === "ada-token" ? Effect.succeed(ada) : Effect.fail(new Unauthorized()), }),)
// The real handlers and middleware, with in-memory Users and fake Tokens.// provideMerge, not provide: HttpApiTest.groups asks for the middleware services in its type.const UsersTest = UsersHttp.pipe( Layer.provideMerge([ValidationLive, AuthorizationLive]), Layer.provide([Users.layerMemory, TokensTest]),)Users.layerMemory has been sitting in Users.ts since part 9 for exactly this. It finally gets used. The test version differs from main.ts in one word, provideMerge, and the comment says why: with plain provide, the suite still runs, but the type of every test ends in Authorization | Validation and refuses to compile (Type 'Authorization' is not assignable to type 'never'). At runtime the group already has its middleware; it’s the test client’s signature that wants to see them.
A client with no server
HttpApiTest.groups is in effect/http-api, marked @stability unstable like the rest of that module. It builds the API from the group layers it finds in context and hands back the same typed client HttpApiClient.make would. Requests go through the real encoding, routing and middleware, and then straight into the handler as an HttpServerRequest, so there’s no socket anywhere.
// A typed client wired straight to the handlers. No server, no port.const makeClient = HttpApiTest.groups(Api, ["users"])
// The client half of Authorization: send Ada's token on every request.const asAda = HttpApiMiddleware.layerClient(Authorization, ({ next, request }) => next(HttpClientRequest.bearerToken(request, "ada-token")),)
layer(Layer.mergeAll(UsersTest, HttpServer.layerServices))("users", (it) => { it.effect("POST /users without a token is Unauthorized", () => Effect.gen(function* () { const client = yield* makeClient const error = yield* client.users .create({ payload: { name: "Grace", email: "grace@example.com" } }) .pipe(Effect.flip) assert.strictEqual(error._tag, "Unauthorized") }), )
it.effect("POST /users with Ada's token creates the user", () => Effect.gen(function* () { const client = yield* makeClient const user = yield* client.users.create({ payload: { name: "Grace", email: "grace@example.com" } }) assert.strictEqual(user.name, "Grace") }).pipe(Effect.provide(asAda)), )})it.effect runs a test that returns an Effect, and layer(...) builds the layer once for the whole block. HttpServer.layerServices covers the platform pieces the pipeline wants (FileSystem, Path, an Etag Generator, HttpPlatform), and leaving it out is a type error naming FileSystem. Effect.flip swaps the channels so the test can look at the error.
Look at the token test. asAda is the only difference between those two tests, and Authorization isn’t requiredForClient, so a test that skips it simply sends no header. The GET tests for Ada and for a missing user (UserNotFound) follow the same shape, so I’ve left them out here.
The two requests the client won’t send
Part 11’s best gotcha was that a blank name without a token gets a 401, not a 400. The typed client can’t test that: it encodes the payload with NewUser first and fails with a SchemaError before anything leaves, same as in part 5. So those two tests go through HttpRouter.toWebHandler, a Request in and a Response out, still in process:
it.effect("a blank name without a token is a 401, not a 400", () => Effect.gen(function* () { const response = yield* call({}, `{"name":"","email":"nope"}`) assert.deepStrictEqual(response, { status: 401, body: { _tag: "Unauthorized" } }) }),)call builds the handler from UsersTest and disposes it in a finalizer. Its sibling test sends the same body with Bearer ada-token and expects the 400. I wrote that one with the messages guessed, and the first run said so:
- Expected+ Received- "message": "x",+ "message": "Expected a value with a length of at least 1",Six tests, around 20 ms of test time; the half second vitest run reports is mostly imports. Stop the Postgres container. They still pass.
Gotchas
- The fake isn’t the database. Memory Ada has no email; Postgres Ada is
ada@example.com.TokensTestnever hashes anything, and nothing here runs part 10’s transaction or writesactor_id. These tests cover the HTTP contract and the middleware. The SQL needs tests against a real Postgres, which is a different setup. layer()shares state. Insrc/part-12/gotchas.test.ts, two tests that each create Grace in onelayer(Users.layerMemory)block get ids 2 and 3. WithEffect.provide(Users.layerMemory)in each test, both get 2. My suite asserts on names, not ids, so its order doesn’t matter.Users.createstill wants aCurrentUser. The memory version never reads it, butUsers’ type comes from the SQLmake, so a test calling it directly has toEffect.provideService(CurrentUser, ada). Over HTTP the middleware does that.it.effectruns onTestClock.Clock.currentTimeMillisis 0, andEffect.sleep("1 second")never wakes up: the test hits vitest’s 5000 ms timeout. Fork the sleep and callTestClock.adjust("1 hour")and it finishes at once with the clock at 3,600,000.it.liveuses the real clock. Nothing in the server sleeps yet. That’s about to change.
Run it
git clone https://github.com/devtrillo/effect-on-the-backendcd effect-on-the-backendgit checkout part-12npm installnpm testNo docker compose, no .env. npm start still needs both, as in part 11. The repo stays on effect 4.0.5, and @effect/vitest matches it.
Every status code from part 11’s table is a test now. If the next change breaks one, I’ll find out from npm test, not from curl a week later.
Next in the series: timeouts, retries and Schedule, where TestClock gets real work.
- Part 13 — Timeouts, retries and Schedule: POST /users calls a flaky mail API: a timeout per attempt, retryTransient with jittered backoff, a 5 second deadline, and an idempotency key. TestClock checks the timing.

