summaryrefslogtreecommitdiff
path: root/tst/hono_proxy.test.ts
blob: 56ed5d9c23f1b668e7a4c1492cce5bacd0808a29 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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();
    });
});