# Testing handlers with @effect/vitest

- Published: 2026-11-19
- Updated: 2026-11-26
- Tags: Effect on the Backend, Effect, TypeScript
- URL: https://devtrillo.com/writing/effect-backend-12-testing-handlers/

> Part 12 of a series that builds one backend server on Node with Effect 4. The code is in [devtrillo/effect-on-the-backend](https://github.com/devtrillo/effect-on-the-backend/tree/part-12), and this part is the `part-12` tag.

[Part 11](/writing/effect-backend-11-auth-middleware-and-current-user/) 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

```sh
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:

```ts title="src/Http.ts (excerpt)"
// 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:

```ts title="src/main.ts (excerpt)"
// 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

```ts title="test/Users.test.ts (excerpt)"
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.

```ts title="test/Users.test.ts (excerpt)"
// 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:

```ts title="test/Users.test.ts (excerpt)"
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:

```text title="npm test (first run, trimmed)"
- 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.

**Quiz:** UsersTest uses Layer.provide instead of Layer.provideMerge for ValidationLive and AuthorizationLive. What happens?

- Every POST answers 500: the middleware is missing at runtime
- It doesn't type-check: Authorization | Validation are left in the requirements
- The token test fails with Unauthorized

**Answer:** It doesn't type-check: Authorization | Validation are left in the requirements — HttpApiTest.groups asks for the endpoints' middleware services in its type. provide hides them, provideMerge passes them through.

- Not "Every POST answers 500: the middleware is missing at runtime": The group got its middleware when it built, so the tests I tried still ran and passed. The problem is only in the types.
- Not "The token test fails with Unauthorized": The token check runs in AuthorizationLive either way. Only what the layer exposes changes.

## Gotchas

- **The fake isn't the database.** Memory Ada has no email; Postgres Ada is `ada@example.com`. `TokensTest` never hashes anything, and nothing here runs part 10's transaction or writes `actor_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.** In `src/part-12/gotchas.test.ts`, two tests that each create Grace in one `layer(Users.layerMemory)` block get ids 2 and 3. With `Effect.provide(Users.layerMemory)` in each test, both get 2. My suite asserts on names, not ids, so its order doesn't matter.
- **`Users.create` still wants a `CurrentUser`.** The memory version never reads it, but `Users`' type comes from the SQL `make`, so a test calling it directly has to `Effect.provideService(CurrentUser, ada)`. Over HTTP the middleware does that.
- **`it.effect` runs on `TestClock`.** `Clock.currentTimeMillis` is 0, and `Effect.sleep("1 second")` never wakes up: the test hits vitest's 5000 ms timeout. Fork the sleep and call `TestClock.adjust("1 hour")` and it finishes at once with the clock at 3,600,000. `it.live` uses the real clock. Nothing in the server sleeps yet. That's about to change.

**Quiz:** An it.effect test calls Effect.sleep('1 second') and nothing else. What happens?

- It passes after one second
- It hangs until vitest's timeout fails it
- It passes at once, because TestClock skips sleeps

**Answer:** It hangs until vitest's timeout fails it — The sleep waits on TestClock. Nothing calls TestClock.adjust, so it times out at 5000 ms.

- Not "It passes after one second": it.effect provides TestClock, which doesn't move on its own. That's it.live.
- Not "It passes at once, because TestClock skips sleeps": TestClock only skips time you move with TestClock.adjust.

## Run it

```sh
git clone https://github.com/devtrillo/effect-on-the-backend
cd effect-on-the-backend
git checkout part-12
npm install
npm test
```

No `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.
