import { afterEach, describe, it } from 'bun:test'; import { expect } from 'chai'; import { Server } from 'node:http'; import type { AddressInfo } from 'node:net'; import type { Context } from '../context'; import { Dispatcher } from '../dispatcher/dispatcher-protocol'; import { HttpRequest } from '../http/http-request'; import { HttpServerUtil } from './http-server'; let server: Server | undefined; afterEach(() => server?.close()); async function serve(dispatch: (ctx: Context) => Promise): Promise { const container = { get: (id: unknown) => (id === Dispatcher ? { dispatch } : undefined) } as any; server = HttpServerUtil.createHttpServer(HttpServerUtil.createHandler(container)); await new Promise(resolve => server!.listen(0, '127.0.0.1', resolve)); return `http://127.0.0.1:${(server.address() as AddressInfo).port}`; } describe('HttpServerUtil', () => { it('dispatches each request with an HttpRequest', async () => { const url = await serve(async ctx => { expect(ctx.request).to.be.instanceOf(HttpRequest); ctx.response.setHeader('content-type', 'application/json'); ctx.response.end(JSON.stringify({ path: ctx.request.path, query: ctx.request.query, host: ctx.request.hostname })); }); const res = await fetch(`${url}/users/1?tag=a&tag=b`); expect(await res.json()).to.deep.equal({ path: '/users/1', query: { tag: ['a', 'b'] }, host: '127.0.0.1' }); expect(res.headers.get('x-powered-by')).to.equal(null); }); it('answers 500 when the dispatcher fails', async () => { const url = await serve(async () => { throw new Error('dispatcher broke'); }); const original = console.error; console.error = () => undefined; try { expect((await fetch(url)).status).to.equal(500); } finally { console.error = original; } }); });