import { Test, TestingModule } from "@nestjs/testing"; import { MetricsController } from "./metrics.controller"; import { PrismaService } from "../prisma/prisma.service"; import type { Response } from "express"; describe("MetricsController", () => { let controller: MetricsController; let prisma: PrismaService; const mockPrismaService = { $queryRaw: jest.fn(), }; const createMockResponse = () => { const res: Partial = {}; res.set = jest.fn().mockReturnValue(res); res.end = jest.fn().mockReturnValue(res); return res as Response; }; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ controllers: [MetricsController], providers: [ { provide: PrismaService, useValue: mockPrismaService, }, ], }).compile(); controller = module.get(MetricsController); prisma = module.get(PrismaService); }); afterEach(() => { jest.clearAllMocks(); }); it("should be defined", () => { expect(controller).toBeDefined(); }); describe("incrementRequestCount", () => { it("should increment static requestCount", async () => { const res = createMockResponse(); mockPrismaService.$queryRaw.mockResolvedValue([{ 1: 1 }]); MetricsController.incrementRequestCount(); await controller.getMetrics(res); expect(res.end).toHaveBeenCalledTimes(1); const output = (res.end as jest.Mock).mock.calls[0][0]; expect(output).toContain("canino_http_requests_total"); }); }); describe("getMetrics", () => { it("should set headers and return prometheus metrics when db is healthy", async () => { const res = createMockResponse(); mockPrismaService.$queryRaw.mockResolvedValue([{ 1: 1 }]); await controller.getMetrics(res); expect(prisma.$queryRaw).toHaveBeenCalled(); expect(res.set).toHaveBeenCalledWith( "Content-Type", "text/plain; version=0.0.4; charset=utf-8", ); expect(res.end).toHaveBeenCalledTimes(1); const output = (res.end as jest.Mock).mock.calls[0][0]; expect(output).toContain("# HELP node_memory_rss_bytes"); expect(output).toContain("# HELP node_memory_heap_used_bytes"); expect(output).toContain("# HELP node_memory_heap_total_bytes"); expect(output).toContain("# HELP node_cpu_user_time_microseconds"); expect(output).toContain("# HELP node_cpu_system_time_microseconds"); expect(output).toContain("# HELP node_app_uptime_seconds"); expect(output).toContain("# HELP canino_db_connected"); expect(output).toContain("canino_db_connected 1"); expect(output).toContain("# HELP canino_http_requests_total"); }); it("should return canino_db_connected 0 when db query throws", async () => { const res = createMockResponse(); mockPrismaService.$queryRaw.mockRejectedValue( new Error("DB Connection Timeout"), ); await controller.getMetrics(res); expect(prisma.$queryRaw).toHaveBeenCalled(); expect(res.set).toHaveBeenCalledWith( "Content-Type", "text/plain; version=0.0.4; charset=utf-8", ); expect(res.end).toHaveBeenCalledTimes(1); const output = (res.end as jest.Mock).mock.calls[0][0]; expect(output).toContain("canino_db_connected 0"); }); }); });