Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
test: cover HookManager, AuditService, and the Postgres-UUID migration
rmyndharis6d5867cc03cd
diff --git a/src/core/hooks/hook-manager.service.spec.ts b/src/core/hooks/hook-manager.service.spec.tsnew file mode 100644index 000000000..8be56cca6--- /dev/null+++ b/src/core/hooks/hook-manager.service.spec.ts@@ -0,0 +1,116 @@+// Hook handlers must satisfy the async HookHandler signature; the test stubs return synchronously,+// so the no-await rule doesn't apply to them here.+/* eslint-disable @typescript-eslint/require-await */+import { HookManager } from './hook-manager.service';++describe('HookManager', () => {+ let hm: HookManager;++ beforeEach(() => {+ hm = new HookManager();+ });++ it('returns {continue:true, data} unchanged when no handlers are registered', async () => {+ const res = await hm.execute('message:received', { a: 1 }, { source: 'test' });+ expect(res).toEqual({ continue: true, data: { a: 1 } });+ });++ it('runs handlers in ascending priority order and propagates the mutated data', async () => {+ hm.register(+ 'p',+ 'message:received',+ async ctx => ({ continue: true, data: [...(ctx.data as string[]), 'late'] }),+ 20,+ );+ hm.register(+ 'p',+ 'message:received',+ async ctx => ({ continue: true, data: [...(ctx.data as string[]), 'early'] }),+ 10,+ );++ const res = await hm.execute<string[]>('message:received', [], { source: 'test' });+ expect(res.data).toEqual(['early', 'late']); // priority 10 runs before 20+ });++ it('stops the chain when a handler returns continue:false', async () => {+ const second = jest.fn();+ hm.register('p', 'message:received', async () => ({ continue: false, data: 'stopped' }), 10);+ hm.register(+ 'p',+ 'message:received',+ async ctx => {+ second();+ return { continue: true, data: ctx.data };+ },+ 20,+ );++ const res = await hm.execute('message:received', 'start', { source: 'test' });+ expect(res).toEqual({ continue: false, data: 'stopped' });+ expect(second).not.toHaveBeenCalled();+ });++ it('isolates a throwing handler — later handlers still run', async () => {+ const later = jest.fn();+ hm.register(+ 'p',+ 'message:received',+ async () => {+ throw new Error('boom');+ },+ 10,+ );+ hm.register(+ 'p',+ 'message:received',+ async ctx => {+ later();+ return { continue: true, data: ctx.data };+ },+ 20,+ );++ const res = await hm.execute('message:received', 'd', { source: 'test' });+ expect(later).toHaveBeenCalledTimes(1);+ expect(res.continue).toBe(true);+ });++ it('isolates a handler that returns result.error — the chain continues', async () => {+ const later = jest.fn();+ hm.register('p', 'message:received', async ctx => ({ continue: true, data: ctx.data, error: new Error('x') }), 10);+ hm.register(+ 'p',+ 'message:received',+ async ctx => {+ later();+ return { continue: true, data: ctx.data };+ },+ 20,+ );++ const res = await hm.execute('message:received', 'd', { source: 'test' });+ expect(later).toHaveBeenCalledTimes(1);+ expect(res.continue).toBe(true);+ });++ it('register/unregister/hasHooks/getHookCount track registrations', () => {+ expect(hm.hasHooks('session:created')).toBe(false);+ const id = hm.register('p', 'session:created', async ctx => ({ continue: true, data: ctx.data }));+ expect(hm.hasHooks('session:created')).toBe(true);+ expect(hm.getHookCount('session:created')).toBe(1);++ hm.unregister(id);+ expect(hm.getHookCount('session:created')).toBe(0);+ expect(hm.hasHooks('session:created')).toBe(false);+ });++ it('unregisterPlugin removes only that plugin’s hooks', () => {+ hm.register('A', 'session:ready', async ctx => ({ continue: true, data: ctx.data }));+ hm.register('A', 'session:ready', async ctx => ({ continue: true, data: ctx.data }));+ hm.register('B', 'session:ready', async ctx => ({ continue: true, data: ctx.data }));++ hm.unregisterPlugin('A');+ expect(hm.getHookCount('session:ready')).toBe(1); // only B remains+ });+});diff --git a/src/database/add-uuid-defaults-migration.spec.ts b/src/database/add-uuid-defaults-migration.spec.tsnew file mode 100644index 000000000..c65e3ee08--- /dev/null+++ b/src/database/add-uuid-defaults-migration.spec.ts@@ -0,0 +1,51 @@+// NOTE: kept OUT of src/database/migrations/ on purpose — the TypeORM migrations glob+// (`migrations/*{.ts,.js}`) would otherwise load this spec as a migration under ts-node+// (the CLI datasource / start:dev) and crash on `describe`.+import { QueryRunner } from 'typeorm';+import { AddUuidDefaultsForPostgres1779235200000 } from './migrations/1779235200000-AddUuidDefaultsForPostgres';++const ALL_TABLES = ['sessions', 'webhooks', 'messages', 'api_keys', 'audit_logs', 'message_batches'];++function makeQueryRunner(type: string, existingTables: Set<string>) {+ return {+ connection: { options: { type } },+ hasTable: jest.fn((t: string) => Promise.resolve(existingTables.has(t))),+ query: jest.fn().mockResolvedValue(undefined),+ };+}++describe('AddUuidDefaultsForPostgres migration', () => {+ const migration = new AddUuidDefaultsForPostgres1779235200000();++ it('is a no-op on SQLite — issues no query and never probes tables', async () => {+ const qr = makeQueryRunner('sqlite', new Set(ALL_TABLES));+ await migration.up(qr as unknown as QueryRunner);+ await migration.down(qr as unknown as QueryRunner);+ expect(qr.query).not.toHaveBeenCalled();+ expect(qr.hasTable).not.toHaveBeenCalled();+ });++ it('on Postgres up() sets a uuid DEFAULT on every existing table', async () => {+ const qr = makeQueryRunner('postgres', new Set(ALL_TABLES));+ await migration.up(qr as unknown as QueryRunner);++ expect(qr.query).toHaveBeenCalledTimes(ALL_TABLES.length);+ expect(qr.query).toHaveBeenCalledWith(+ 'ALTER TABLE "sessions" ALTER COLUMN "id" SET DEFAULT gen_random_uuid()::varchar',+ );+ });++ it('skips tables that do not exist', async () => {+ const qr = makeQueryRunner('postgres', new Set(['sessions', 'messages']));+ await migration.up(qr as unknown as QueryRunner);+ expect(qr.query).toHaveBeenCalledTimes(2);+ });++ it('on Postgres down() drops the DEFAULT on every existing table', async () => {+ const qr = makeQueryRunner('postgres', new Set(ALL_TABLES));+ await migration.down(qr as unknown as QueryRunner);++ expect(qr.query).toHaveBeenCalledTimes(ALL_TABLES.length);+ expect(qr.query).toHaveBeenCalledWith('ALTER TABLE "api_keys" ALTER COLUMN "id" DROP DEFAULT');+ });+});diff --git a/src/modules/audit/audit.service.spec.ts b/src/modules/audit/audit.service.spec.tsnew file mode 100644index 000000000..c3463019c--- /dev/null+++ b/src/modules/audit/audit.service.spec.ts@@ -0,0 +1,89 @@+import { Repository, Between } from 'typeorm';+import { AuditService } from './audit.service';+import { AuditLog, AuditAction, AuditSeverity } from './entities/audit-log.entity';++describe('AuditService', () => {+ let service: AuditService;+ let repo: { create: jest.Mock; save: jest.Mock; findAndCount: jest.Mock; delete: jest.Mock };++ beforeEach(() => {+ repo = {+ create: jest.fn((e: Partial<AuditLog>) => e),+ save: jest.fn((e: Partial<AuditLog>) => Promise.resolve({ id: 'a1', ...e })),+ findAndCount: jest.fn().mockResolvedValue([[], 0]),+ delete: jest.fn().mockResolvedValue({ affected: 0 }),+ };+ service = new AuditService(repo as unknown as Repository<AuditLog>);+ });++ it('log() persists the action/severity and null-coalesces absent context fields', async () => {+ await service.log(AuditAction.SESSION_CREATED, { sessionId: 's1' }, AuditSeverity.WARN);++ expect(repo.create).toHaveBeenCalledWith(+ expect.objectContaining({+ action: AuditAction.SESSION_CREATED,+ severity: AuditSeverity.WARN,+ sessionId: 's1',+ apiKeyId: null,+ ipAddress: null,+ statusCode: null,+ }),+ );+ expect(repo.save).toHaveBeenCalledTimes(1);+ });++ it('logInfo/logWarn/logError map to the right severity', async () => {+ await service.logInfo(AuditAction.API_KEY_USED);+ await service.logWarn(AuditAction.API_KEY_AUTH_FAILED);+ await service.logError(AuditAction.MESSAGE_FAILED);+ const severities = (repo.create.mock.calls as unknown[][]).map(c => (c[0] as { severity: AuditSeverity }).severity);+ expect(severities).toEqual([AuditSeverity.INFO, AuditSeverity.WARN, AuditSeverity.ERROR]);+ });++ it('findAll applies provided filters with default take/skip', async () => {+ await service.findAll({ action: AuditAction.SESSION_STARTED, severity: AuditSeverity.INFO });+ expect(repo.findAndCount).toHaveBeenCalledWith(+ expect.objectContaining({+ where: { action: AuditAction.SESSION_STARTED, severity: AuditSeverity.INFO },+ order: { createdAt: 'DESC' },+ take: 50,+ skip: 0,+ }),+ );+ });++ it('findAll uses Between only when BOTH dates are present', async () => {+ const start = new Date('2026-01-01T00:00:00Z');+ const end = new Date('2026-02-01T00:00:00Z');+ await service.findAll({ startDate: start, endDate: end, limit: 10, offset: 5 });+ const arg = (repo.findAndCount.mock.calls as unknown[][])[0][0] as {+ where: Record<string, unknown>;+ take: number;+ skip: number;+ };+ expect(arg.where.createdAt).toEqual(Between(start, end));+ expect(arg.take).toBe(10);+ expect(arg.skip).toBe(5);++ repo.findAndCount.mockClear();+ await service.findAll({ startDate: start }); // only one date → no Between+ const arg2 = (repo.findAndCount.mock.calls as unknown[][])[0][0] as { where: Record<string, unknown> };+ expect(arg2.where.createdAt).toBeUndefined();+ });++ it('cleanup deletes rows older than the cutoff and returns the affected count', async () => {+ repo.delete.mockResolvedValue({ affected: 7 });+ const removed = await service.cleanup(30);++ expect(removed).toBe(7);+ const arg = (repo.delete.mock.calls as unknown[][])[0][0] as { createdAt: unknown };+ const cutoff = (arg.createdAt as { value: Date }).value; // LessThan(cutoff)+ const expected = Date.now() - 30 * 24 * 60 * 60 * 1000;+ expect(Math.abs(cutoff.getTime() - expected)).toBeLessThan(10_000);+ });++ it('cleanup returns 0 when the driver reports a null affected count', async () => {+ repo.delete.mockResolvedValue({ affected: null });+ expect(await service.cleanup(10)).toBe(0);+ });+});