import { TavusClient, TavusError, TavusErrorType, RetryConfig } from '../shared/utils/api-clients/tavus-client'; // Mock fetch globally global.fetch = jest.fn(); describe('TavusClient Error Handling and Video Visibility', () => { let tavusClient: TavusClient; let mockFetch: jest.MockedFunction; beforeEach(() => { // Reset mocks jest.clearAllMocks(); mockFetch = global.fetch as jest.MockedFunction; // Create client with debug enabled tavusClient = new TavusClient({ debug: true, }); }); describe('Video Visibility Management', () => { beforeEach(async () => { // Mock successful initialization mockFetch.mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({ success: true, data: { replicas: [] } }), } as Response); await tavusClient.initialize(); }); it('should set user video visibility with options', () => { const consoleSpy = jest.spyOn(console, 'log').mockImplementation(); tavusClient.setUserVideoVisibility(true, { changedBy: 'test-user', reason: 'test-reason', }); const state = tavusClient.getVideoVisibilityState(); expect(state.isVisible).toBe(true); expect(state.changedBy).toBe('test-user'); expect(state.reason).toBe('test-reason'); expect(state.lastChanged).toBeInstanceOf(Date); expect(consoleSpy).toHaveBeenCalledWith( 'User video visibility set to: true', expect.objectContaining({ changedBy: 'test-user', reason: 'test-reason', }) ); consoleSpy.mockRestore(); }); it('should toggle video visibility', () => { // Start with visible tavusClient.setUserVideoVisibility(true); expect(tavusClient.getVideoVisibilityState().isVisible).toBe(true); // Toggle to hidden tavusClient.toggleVideoVisibility({ reason: 'toggle-test' }); expect(tavusClient.getVideoVisibilityState().isVisible).toBe(false); // Toggle back to visible tavusClient.toggleVideoVisibility({ reason: 'toggle-back' }); expect(tavusClient.getVideoVisibilityState().isVisible).toBe(true); }); it('should throw error when setting visibility before initialization', () => { const uninitializedClient = new TavusClient({ debug: true }); expect(() => { uninitializedClient.setUserVideoVisibility(true); }).toThrow('TavusClient must be initialized before setting video visibility'); }); it('should throw error for invalid visibility value', () => { expect(() => { tavusClient.setUserVideoVisibility('true' as any); }).toThrow('Video visibility must be a boolean value'); }); it('should emit video visibility change event', () => { const eventSpy = jest.fn(); // Mock window.dispatchEvent if available if (typeof window !== 'undefined') { const originalDispatchEvent = window.dispatchEvent; window.dispatchEvent = eventSpy; tavusClient.setUserVideoVisibility(false, { reason: 'event-test' }); expect(eventSpy).toHaveBeenCalledWith( expect.objectContaining({ type: 'tavus-video-visibility-change', detail: expect.objectContaining({ isVisible: false, source: 'TavusClient', }), }) ); // Restore original window.dispatchEvent = originalDispatchEvent; } else { // Skip test if window is not available expect(true).toBe(true); } }); }); describe('Error Handling and Statistics', () => { beforeEach(async () => { // Mock successful initialization mockFetch.mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({ success: true, data: { replicas: [] } }), } as Response); await tavusClient.initialize(); }); it('should track error statistics', () => { const stats = tavusClient.getErrorStats(); expect(stats.totalErrors).toBe(0); expect(stats.errorCounts).toEqual({ authentication: 0, network: 0, rate_limit: 0, validation: 0, server: 0, timeout: 0, unknown: 0, }); expect(stats.lastError).toBeUndefined(); }); it('should clear error statistics', () => { // First, trigger an error mockFetch.mockRejectedValueOnce(new Error('Network error')); return tavusClient.getReplicas().catch(() => { const statsBefore = tavusClient.getErrorStats(); expect(statsBefore.totalErrors).toBeGreaterThan(0); tavusClient.clearErrorStats(); const statsAfter = tavusClient.getErrorStats(); expect(statsAfter.totalErrors).toBe(0); expect(statsAfter.lastError).toBeUndefined(); }); }); it('should update retry configuration', () => { const newConfig: Partial = { maxRetries: 5, baseDelay: 2000, exponentialBackoff: false, }; tavusClient.updateRetryConfig(newConfig); // Verify the configuration was updated by checking error stats // (the retry config is private, so we test it indirectly) const stats = tavusClient.getErrorStats(); expect(stats).toBeDefined(); }); }); describe('Conversation Management with Error Handling', () => { beforeEach(async () => { // Mock successful initialization mockFetch.mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({ success: true, data: { replicas: [] } }), } as Response); await tavusClient.initialize(); }); it('should create conversation successfully', async () => { const conversationResponse = { conversationId: 'conv-123', roomUrl: 'https://room.example.com/conv-123', accessToken: 'token-123', isActive: true, startTime: new Date().toISOString(), replicaId: 'rf4703150052', personaId: 'p48fdf065d6b', }; mockFetch.mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({ success: true, data: conversationResponse }), } as Response); const result = await tavusClient.createConversation({ replicaId: 'rf4703150052', personaId: 'p48fdf065d6b', properties: { participantLeftTimeout: 0, language: 'english', enableVideo: true, enableAudio: true, }, }); // The response includes data and success properties expect(result.data).toEqual(conversationResponse); expect(mockFetch).toHaveBeenCalledWith( 'https://tavusapi.com/v2/conversations', expect.objectContaining({ method: 'POST', headers: expect.objectContaining({ 'Content-Type': 'application/json', 'x-api-key': '3e787ab4afad481cbe1a8a3c61295d70', }), body: JSON.stringify({ replica_id: 'rf4703150052', persona_id: 'p48fdf065d6b', properties: { participant_left_timeout: 0, language: 'english', enable_video: true, enable_audio: true, }, }), }) ); }); it('should validate conversation request parameters', async () => { // Test missing replicaId await expect( tavusClient.createConversation({ replicaId: '', personaId: 'p48fdf065d6b', }) ).rejects.toThrow('replicaId is required and must be a string'); // Test missing personaId await expect( tavusClient.createConversation({ replicaId: 'rf4703150052', personaId: '', }) ).rejects.toThrow('personaId is required and must be a string'); // Test invalid participantLeftTimeout await expect( tavusClient.createConversation({ replicaId: 'rf4703150052', personaId: 'p48fdf065d6b', properties: { participantLeftTimeout: -1, }, }) ).rejects.toThrow('participantLeftTimeout must be a non-negative number'); }); it('should handle conversation creation errors', async () => { mockFetch.mockResolvedValueOnce({ ok: false, status: 400, json: async () => ({ success: false, error: 'Invalid replica ID', statusCode: 400 }), } as Response); await expect( tavusClient.createConversation({ replicaId: 'invalid-replica', personaId: 'p48fdf065d6b', }) ).rejects.toThrow('Invalid replica ID'); const stats = tavusClient.getErrorStats(); expect(stats.totalErrors).toBeGreaterThan(0); }); it('should get conversation details', async () => { const conversationData = { conversationId: 'conv-123', roomUrl: 'https://room.example.com/conv-123', accessToken: 'token-123', isActive: true, startTime: new Date().toISOString(), replicaId: 'rf4703150052', personaId: 'p48fdf065d6b', }; mockFetch.mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({ success: true, data: conversationData }), } as Response); const result = await tavusClient.getConversation('conv-123'); // The response includes data and success properties expect(result.data).toEqual(conversationData); expect(mockFetch).toHaveBeenCalledWith( 'https://tavusapi.com/v2/conversations/conv-123', expect.objectContaining({ method: 'GET', }) ); }); it('should end conversation successfully', async () => { mockFetch.mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({ success: true }), } as Response); await expect( tavusClient.endConversation('conv-123') ).resolves.toBeUndefined(); expect(mockFetch).toHaveBeenCalledWith( 'https://tavusapi.com/v2/conversations/conv-123', expect.objectContaining({ method: 'DELETE', }) ); }); }); describe('Enhanced Video Streaming Error Handling', () => { beforeEach(async () => { // Mock successful initialization mockFetch.mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({ success: true, data: { replicas: [] } }), } as Response); await tavusClient.initialize(); }); it('should validate session ID for video streaming', async () => { await expect( tavusClient.startVideoStream('', 'medium') ).rejects.toThrow('Session ID is required and must be a string'); await expect( tavusClient.startVideoStream(null as any, 'medium') ).rejects.toThrow('Session ID is required and must be a string'); }); it('should handle video streaming errors gracefully', async () => { mockFetch.mockResolvedValueOnce({ ok: false, status: 404, json: async () => ({ success: false, error: 'Session not found', statusCode: 404 }), } as Response); await expect( tavusClient.startVideoStream('invalid-session', 'medium') ).rejects.toThrow('Session not found'); const stats = tavusClient.getErrorStats(); expect(stats.totalErrors).toBeGreaterThan(0); expect(stats.lastError?.type).toBe('server'); }); it('should handle network errors in video streaming', async () => { mockFetch.mockRejectedValueOnce(new Error('Network timeout')); await expect( tavusClient.startVideoStream('session-123', 'medium') ).rejects.toThrow('Network timeout'); const stats = tavusClient.getErrorStats(); expect(stats.totalErrors).toBeGreaterThan(0); expect(stats.lastError?.type).toBe('network'); }); }); describe('Retry Logic', () => { beforeEach(async () => { // Mock successful initialization mockFetch.mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({ success: true, data: { replicas: [] } }), } as Response); await tavusClient.initialize(); }); it('should retry on server errors', async () => { // First call fails with 500, second succeeds mockFetch .mockResolvedValueOnce({ ok: false, status: 500, json: async () => ({ success: false, error: 'Internal server error', statusCode: 500 }), } as Response) .mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({ success: true, data: { replicas: [] } }), } as Response); const result = await tavusClient.getReplicas(); expect(mockFetch).toHaveBeenCalledTimes(2); expect(result).toEqual([]); }); it('should not retry on validation errors', async () => { mockFetch.mockResolvedValueOnce({ ok: false, status: 400, json: async () => ({ success: false, error: 'Bad request', statusCode: 400 }), } as Response); await expect( tavusClient.getReplicas() ).rejects.toThrow('Bad request'); // Should not retry validation errors expect(mockFetch).toHaveBeenCalledTimes(1); }); }); });