import type { KafkaConnectionCredentials } from './types'; import { kafkaClient } from './client'; import { getKafkaConnection } from './connection'; jest.mock('./connection'); describe('kafkaClient', () => { const mockSend = jest.fn(); const mockEncode = jest.fn(); const mockLogger = { error: jest.fn(), info: jest.fn(), // eslint-disable-next-line no-undef } as unknown as Console; beforeEach(() => { (getKafkaConnection as jest.Mock).mockResolvedValue({ send: mockSend, encode: mockEncode, }); }); afterEach(() => { jest.clearAllMocks(); }); it('should handle connection error', async () => { (getKafkaConnection as jest.Mock).mockRejectedValue(new Error('Connection error')); await kafkaClient( 'topic', () => 'id', [], {} as KafkaConnectionCredentials, mockLogger ); expect(mockLogger.error).toHaveBeenCalledWith(new Error('Connection error')); }); it('should handle message encoding error', async () => { mockEncode.mockRejectedValue(new Error('Encoding error')); await kafkaClient( 'topic', () => 'id', ['test message', 'test message 2'], {} as KafkaConnectionCredentials, mockLogger ); expect(mockLogger.error).toHaveBeenNthCalledWith(1, 'Kafka message failed to encode', new Error('Encoding error')); expect(mockLogger.error).toHaveBeenNthCalledWith(2, 'Kafka message failed to encode', new Error('Encoding error')); expect(mockLogger.error).toHaveBeenNthCalledWith(3, 'No kafka messages to send'); }); it('should handle no messages to send', async () => { await kafkaClient( 'topic', () => 'id', [], {} as KafkaConnectionCredentials, mockLogger ); expect(mockLogger.error).toHaveBeenCalledWith('No kafka messages to send'); }); it('should handle message sending error', async () => { mockEncode.mockResolvedValue(Buffer.from('message')); mockSend.mockRejectedValue(new Error('Sending error')); await kafkaClient( 'topic', () => 'id', ['test message'], {} as KafkaConnectionCredentials, mockLogger ); expect(mockLogger.error).toHaveBeenCalledWith(new Error('Sending error')); }); it('should handle successful scenario', async () => { mockEncode.mockResolvedValue(Buffer.from('message')); mockSend.mockResolvedValue([{ timestamp: 'timestamp', errorCode: null }]); await kafkaClient( 'topic', () => 'id', ['test message'], {} as KafkaConnectionCredentials, mockLogger ); expect(mockLogger.info).toHaveBeenCalledWith('Message sent: Topic: topic, Key:id'); }); });