// Mock dependencies jest.mock('../../../../../services/email/core/EmailClient', () => { return jest.fn().mockImplementation(() => ({ initialize: jest.fn().mockResolvedValue(), sendEmail: jest.fn().mockResolvedValue({ success: true, messageId: 'msg-123' }), })); }); jest.mock('../../../../../services/email/core/TemplateManager', () => { return jest.fn().mockImplementation(() => ({ initialize: jest.fn().mockResolvedValue(), renderTemplate: jest.fn().mockResolvedValue('Test'), })); }); jest.mock('../../../../../utils/logger', () => ({ info: jest.fn(), error: jest.fn(), warn: jest.fn(), })); const AlphaInvitationEmailService = require('../../../../../services/email/domain/AlphaInvitationEmailService'); describe('AlphaInvitationEmailService', () => { let service; const originalEnv = process.env; beforeEach(() => { jest.clearAllMocks(); process.env = { ...originalEnv, FRONTEND_URL: 'http://localhost:3000' }; service = new AlphaInvitationEmailService(); }); afterEach(() => { process.env = originalEnv; }); describe('initialize', () => { it('should initialize only once', async () => { await service.initialize(); await service.initialize(); expect(service.emailClient.initialize).toHaveBeenCalledTimes(1); expect(service.templateManager.initialize).toHaveBeenCalledTimes(1); }); }); describe('sendAlphaInvitation', () => { const email = 'john@example.com'; const code = 'ALPHA-123-XYZ'; it('should send alpha invitation email with correct variables', async () => { const result = await service.sendAlphaInvitation(email, code); expect(result.success).toBe(true); expect(service.templateManager.renderTemplate).toHaveBeenCalledWith( 'alphaInvitationToUser', expect.objectContaining({ code: 'ALPHA-123-XYZ', email: 'john@example.com', frontendUrl: 'http://localhost:3000', title: 'Welcome to Alpha Testing!', }) ); expect(service.emailClient.sendEmail).toHaveBeenCalledWith( 'john@example.com', 'Your Alpha Access Code - Village Share', expect.any(String) ); }); it('should include code in message variable', async () => { await service.sendAlphaInvitation(email, code); expect(service.templateManager.renderTemplate).toHaveBeenCalledWith( 'alphaInvitationToUser', expect.objectContaining({ message: expect.stringContaining('ALPHA-123-XYZ'), }) ); }); it('should handle errors gracefully', async () => { service.templateManager.renderTemplate.mockRejectedValueOnce(new Error('Template error')); const result = await service.sendAlphaInvitation(email, code); expect(result.success).toBe(false); expect(result.error).toBe('Template error'); }); }); });