import { describe, expect, it, vi } from 'vitest'; import { ServiceUnavailableException } from '@nestjs/common'; import { HealthService } from './health.service.js'; describe('HealthService', () => { it('reports liveness and readiness when dependencies are healthy', async () => { const database = { health: vi.fn().mockResolvedValue(undefined) }; const redis = { health: vi.fn().mockResolvedValue(undefined) }; const service = new HealthService( database as never, redis as never, { getOrThrow: () => 50 } as never, ); expect(service.getLiveness()).toEqual({ status: 'ok' }); await expect(service.getReadiness()).resolves.toEqual({ status: 'ok' }); }); it('rejects readiness when a dependency is unavailable', async () => { const database = { health: vi.fn().mockRejectedValue(new Error('down')), }; const redis = { health: vi.fn().mockResolvedValue(undefined) }; const service = new HealthService( database as never, redis as never, { getOrThrow: () => 50 } as never, ); await expect(service.getReadiness()).rejects.toBeInstanceOf( ServiceUnavailableException, ); }); it('rejects readiness when Redis alone is unavailable', async () => { const database = { health: vi.fn().mockResolvedValue(undefined) }; const redis = { health: vi.fn().mockRejectedValue(new Error('down')), }; const service = new HealthService( database as never, redis as never, { getOrThrow: () => 50 } as never, ); await expect(service.getReadiness()).rejects.toBeInstanceOf( ServiceUnavailableException, ); }); it('keeps liveness healthy while draining', async () => { const service = new HealthService( { health: vi.fn() } as never, { health: vi.fn() } as never, { getOrThrow: () => 50 } as never, ); service.setDraining(); expect(service.getLiveness()).toEqual({ status: 'ok' }); await expect(service.getReadiness()).rejects.toThrow( 'Service is shutting down', ); }); it('answers not-ready during drain without probing dependencies', async () => { const database = { health: vi.fn().mockResolvedValue(undefined) }; const redis = { health: vi.fn().mockResolvedValue(undefined) }; const service = new HealthService( database as never, redis as never, { getOrThrow: () => 50 } as never, ); service.setDraining(); await expect(service.getReadiness()).rejects.toThrow( 'Service is shutting down', ); // Дрейн обязан отвечать сразу: проба LB не должна ждать зависимости, // когда реплика уже выходит из ротации. expect(database.health).not.toHaveBeenCalled(); expect(redis.health).not.toHaveBeenCalled(); }); it('fails readiness within the budget when a dependency hangs', async () => { const database = { health: vi.fn(() => new Promise(() => {})) }; const redis = { health: vi.fn().mockResolvedValue(undefined) }; const service = new HealthService( database as never, redis as never, { getOrThrow: () => 20 } as never, ); await expect(service.getReadiness()).rejects.toBeInstanceOf( ServiceUnavailableException, ); }); });