Testing Middleware Behavior in HttpApi Endpoints

How to test middleware behavior in HttpApi endpoints?

Hi everyone! 👋

I'm working with Effect's HttpApi and trying to test middleware behavior, specifically JWT bearer authentication middleware. I have a protected endpoint that uses JwtSpec middleware, and I want to test different scenarios:

1. Missing authorization header (should fail with 403)
2. Invalid authorization header format (should fail with 401)
3. Valid bearer token (should succeed)

Full code https://effect.website/play/#0ae1977b6282

Here's my current working solution using HttpApiClient.makeWith:

import { HttpApiBuilder, HttpApiClient, HttpClient } from '@effect/platform'
import { NodeHttpServer } from '@effect/platform-node'

// Test setup with mocked JWT middleware
const TestJwt = Layer.succeed(JwtSpec, {
  bearer: (token: Redacted.Redacted<string>) =>
    Effect.succeed({
      jwtPayload: new JWTPayload({ /* ... */ }),
      jwtRawToken: token,
    }),
})

const LayerTest = HttpGroupTest(
  GroupApiSpec,
  GroupProtectedLive.pipe(
    Layer.provide(TestJwt),
    Layer.provide(TestConfigProvider),
  ),
)

describe('Protected Route', () => {
  // ❌ IT DOES NOT WORK
  it.effect('should fail without authorization header', () =>
    Effect.gen(function* () {
      const client = yield* HttpApiClient.make(GroupApiSpec)
      const error = yield* client.Protected.test().pipe(Effect.flip)
      expect(error).toEqual(
        expect.objectContaining({ _tag: 'HttpApiError', status: 403 })
      )
    }).pipe(Effect.provide(LayerTest))
  )


[continued]
Was this page helpful?