diff options
Diffstat (limited to 'tst/hono_proxy.test.ts')
| -rw-r--r-- | tst/hono_proxy.test.ts | 90 |
1 files changed, 90 insertions, 0 deletions
diff --git a/tst/hono_proxy.test.ts b/tst/hono_proxy.test.ts new file mode 100644 index 0000000..56ed5d9 --- /dev/null +++ b/tst/hono_proxy.test.ts @@ -0,0 +1,90 @@ +import type { BaseRequest } from '../lib/index'; + +type HonoHandler = (c: { req: BaseRequest }) => Promise<Response>; + +const makeBaseRequest = (overrides: Partial<BaseRequest> = {}): BaseRequest => ({ + url: 'https://example.com/hello', + method: 'GET', + header: () => ({}), + formData: async () => new FormData(), + json: async () => ({ ok: true }), + text: async () => 'hi', + param: () => undefined, + query: () => ({}), + queries: () => ({}), + ...overrides, +}); + +let routeHandler: HonoHandler | undefined; +const allMock = jest.fn((_path: string, handler: HonoHandler) => { + routeHandler = handler; +}); + +class Hono { + public all = allMock; + public async fetch(_r: Request) { + if (!routeHandler) throw new Error('route handler not registered'); + return await routeHandler({ req: makeBaseRequest() }); + } +} + +const serveMock = jest.fn(); + +jest.mock('hono', () => ({ Hono })); +jest.mock('@hono/node-server', () => ({ serve: serveMock })); + +describe('server/hono/proxy (HonoProxy)', () => { + beforeEach(() => { + jest.resetModules(); + serveMock.mockReset(); + allMock.mockClear(); + routeHandler = undefined; + + jest.spyOn(globalThis.crypto, 'randomUUID').mockReturnValue('00000000-0000-0000-0000-000000000000'); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + test('wires Server.serve into hono and returns right', async () => { + const log = jest.spyOn(console, 'log').mockImplementation(() => undefined); + const err = jest.spyOn(console, 'error').mockImplementation(() => undefined); + + const handlers: Record<string, () => void> = {}; + jest.spyOn(process, 'on').mockImplementation(((evt: string, cb: () => void) => { + handlers[evt] = cb; + return process; + }) as any); + + serveMock.mockImplementation((opts: any) => { + queueMicrotask(() => opts.fetch(new Request('http://x'))); + return { + close: (cb: (err?: Error) => void) => cb(undefined), + }; + }); + + const { HonoProxy, PenguenoResponse } = await import('../lib/index'); + + const server = { + serve: jest.fn(async (req: any) => new PenguenoResponse(req, 'ok', { status: 200, headers: {} })), + }; + + const proxy = new HonoProxy(server as any); + const p = proxy.serve(3001, '127.0.0.1'); + + // allow awaitClose to register handlers + await new Promise((r) => setImmediate(r)); + handlers.SIGINT(); + + const res = await p; + expect(res.left().present()).toBe(false); + + expect(serveMock).toHaveBeenCalledWith(expect.objectContaining({ port: 3001, hostname: '127.0.0.1' })); + expect(allMock).toHaveBeenCalledWith('*', expect.any(Function)); + expect(server.serve).toHaveBeenCalledTimes(1); + + log.mockRestore(); + err.mockRestore(); + }); +}); |
