import { describe, test, expect, beforeEach, afterEach } from 'bun:test'; import { GroupSyncService } from '../../../src/services/group-sync'; const envBackup = { ...process.env }; let originalSyncMembers: any; let originalSyncGroups: any; function sleep(ms: number) { return new Promise(res => setTimeout(res, ms)); } describe('GroupSyncService - scheduler de miembros', () => { beforeEach(() => { originalSyncMembers = GroupSyncService.syncMembersForActiveGroups; originalSyncGroups = GroupSyncService.syncGroups; }); afterEach(() => { GroupSyncService.stopMembersScheduler(); GroupSyncService.stopGroupsScheduler(); GroupSyncService.syncMembersForActiveGroups = originalSyncMembers; GroupSyncService.syncGroups = originalSyncGroups; process.env = envBackup; }); test('no arranca en entorno de test', async () => { process.env = { ...envBackup, NODE_ENV: 'test' }; let called = 0; GroupSyncService.syncMembersForActiveGroups = async () => { called++; return { groups: 0, added: 0, updated: 0, deactivated: 0 }; }; GroupSyncService.startMembersScheduler(); await sleep(100); expect(called).toBe(0); }); test('arranca en producción y ejecuta según intervalo', async () => { process.env = { ...envBackup, NODE_ENV: 'production', GROUP_MEMBERS_SYNC_INTERVAL_MS: '30' }; let called = 0; GroupSyncService.syncMembersForActiveGroups = async () => { called++; return { groups: 0, added: 0, updated: 0, deactivated: 0 }; }; GroupSyncService.startMembersScheduler(); await sleep(120); GroupSyncService.stopMembersScheduler(); expect(called).toBeGreaterThanOrEqual(1); }); test('groups scheduler no arranca en entorno de test', async () => { process.env = { ...envBackup, NODE_ENV: 'test' }; let called = 0; GroupSyncService.syncGroups = async () => { called++; return { added: 0, updated: 0 }; }; GroupSyncService.startGroupsScheduler(); await sleep(100); expect(called).toBe(0); expect(GroupSyncService.getSecondsUntilNextGroupSync()).toBeNull(); }); test('groups scheduler arranca en producción y programa next tick', async () => { process.env = { ...envBackup, NODE_ENV: 'production', GROUP_SYNC_INTERVAL_MS: '30' }; let called = 0; GroupSyncService.syncGroups = async () => { called++; return { added: 0, updated: 0 }; }; GroupSyncService.startGroupsScheduler(); const secs1 = GroupSyncService.getSecondsUntilNextGroupSync(); expect(secs1).not.toBeNull(); expect(Number(secs1)).toBeGreaterThan(0); await sleep(120); GroupSyncService.stopGroupsScheduler(); expect(called).toBeGreaterThanOrEqual(1); }); });