|
| 1 | +import { jest, describe, it, expect, beforeEach } from "@jest/globals"; |
| 2 | +import { EventEmitter } from "events"; |
| 3 | + |
| 4 | +const mockGet = jest.fn(); |
| 5 | + |
| 6 | +jest.unstable_mockModule("http", () => ({ |
| 7 | + __esModule: true, |
| 8 | + default: { get: (...args: unknown[]) => mockGet(...args) }, |
| 9 | + get: (...args: unknown[]) => mockGet(...args), |
| 10 | +})); |
| 11 | + |
| 12 | +let runHealthcheck: typeof import("../src/healthcheck").runHealthcheck; |
| 13 | + |
| 14 | +beforeEach(async () => { |
| 15 | + jest.resetModules(); |
| 16 | + mockGet.mockReset(); |
| 17 | + ({ runHealthcheck } = await import("../src/healthcheck")); |
| 18 | +}); |
| 19 | + |
| 20 | +function mockResponse(path: string, status: number, data: string) { |
| 21 | + mockGet.mockImplementationOnce( |
| 22 | + ( |
| 23 | + _opts: unknown, |
| 24 | + cb: (res: EventEmitter & { statusCode?: number }) => void, |
| 25 | + ) => { |
| 26 | + const res = new EventEmitter() as EventEmitter & { statusCode?: number }; |
| 27 | + res.statusCode = status; |
| 28 | + cb(res); |
| 29 | + process.nextTick(() => { |
| 30 | + if (data) res.emit("data", data); |
| 31 | + res.emit("end"); |
| 32 | + }); |
| 33 | + return { on: jest.fn() } as unknown as EventEmitter; |
| 34 | + }, |
| 35 | + ); |
| 36 | +} |
| 37 | + |
| 38 | +describe("runHealthcheck", () => { |
| 39 | + it("returns true on healthy response", async () => { |
| 40 | + mockResponse("/ping", 200, "pong"); |
| 41 | + mockResponse( |
| 42 | + "/health", |
| 43 | + 200, |
| 44 | + JSON.stringify({ botsRunning: true, mqttConnected: true }), |
| 45 | + ); |
| 46 | + await expect(runHealthcheck()).resolves.toBe(true); |
| 47 | + }); |
| 48 | + |
| 49 | + it("returns false on ping failure", async () => { |
| 50 | + mockResponse("/ping", 500, ""); |
| 51 | + await expect(runHealthcheck()).resolves.toBe(false); |
| 52 | + }); |
| 53 | + |
| 54 | + it("returns false on invalid health", async () => { |
| 55 | + mockResponse("/ping", 200, "pong"); |
| 56 | + mockResponse("/health", 200, "oops"); |
| 57 | + await expect(runHealthcheck()).resolves.toBe(false); |
| 58 | + }); |
| 59 | +}); |
0 commit comments