/** * Tests for Tavus Conversation and WebRTC functionality * * Tests conversation creation, WebRTC connection, and video streaming * with the Tavus.io API. */ // Mock Daily.js module first jest.mock('@daily-co/daily-js', () => ({ __esModule: true, default: { createFrame: jest.fn().mockReturnValue({ on: jest.fn(), join: jest.fn().mockResolvedValue(undefined), participants: jest.fn().mockReturnValue({}), }), }, })); import { TavusClient, TavusConfig, ConversationRequest } from '../libs/shared/utils/src/api-clients/tavus-client'; // Mock fetch for testing const mockFetch = jest.fn(); global.fetch = mockFetch; // Get the mocked Daily.js const mockDailyIframe = require('@daily-co/daily-js').default; const mockDailyCall = mockDailyIframe.createFrame(); // Mock MediaStream for Daily.js const mockMediaStream = { getTracks: jest.fn().mockReturnValue([]), }; // Mock MediaStreamTrack for video streams const mockMediaStreamTrack = { kind: 'video', id: 'mock-track-id', enabled: true, muted: false, readyState: 'live', }; // Mock document.createElement for Daily.js const mockCreateElement = jest.fn(); mockCreateElement.mockReturnValue({ src: '', crossOrigin: '', onload: null, onerror: null, }); // Mock requestAnimationFrame const mockRequestAnimationFrame = jest.fn(); // Mock window object for Daily.js Object.defineProperty(global, 'window', { value: { document: { createElement: mockCreateElement, head: { appendChild: jest.fn(), }, }, Daily: mockDailyIframe, }, writable: true, }); // Mock global objects Object.defineProperty(global, 'document', { value: { createElement: mockCreateElement, head: { appendChild: jest.fn(), }, }, writable: true, }); Object.defineProperty(global, 'requestAnimationFrame', { value: mockRequestAnimationFrame, writable: true, }); Object.defineProperty(global, 'MediaStreamTrack', { value: jest.fn().mockImplementation(() => mockMediaStreamTrack), writable: true, }); Object.defineProperty(global, 'MediaStream', { value: jest.fn().mockImplementation(() => mockMediaStream), writable: true, }); describe('Tavus Conversation and WebRTC', () => { let tavusClient: TavusClient; let mockConfig: TavusConfig; beforeEach(() => { // Reset mocks mockFetch.mockClear(); mockCreateElement.mockClear(); mockRequestAnimationFrame.mockClear(); mockDailyCall.on.mockClear(); mockDailyCall.join.mockClear(); mockDailyCall.participants.mockClear(); mockDailyIframe.createFrame.mockClear(); // Create mock config mockConfig = { apiKey: 'test-api-key-123', debug: true, }; // Create client instance tavusClient = new TavusClient(mockConfig); }); describe('Conversation Creation', () => { beforeEach(async () => { // Mock successful initialization mockFetch.mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({ replicas: [] }), }); await tavusClient.initialize(); }); it('should create conversation successfully', async () => { const mockConversationResponse = { conversation_id: 'c123456', conversation_url: 'https://tavus.daily.co/c123456', status: 'active', replica_id: 'rf4703150052', persona_id: 'p48fdf065d6b', created_at: '2024-01-01T00:00:00Z', }; mockFetch.mockResolvedValueOnce({ ok: true, status: 200, json: async () => mockConversationResponse, }); const conversationRequest: ConversationRequest = { replicaId: 'rf4703150052', personaId: 'p48fdf065d6b', properties: { max_call_duration: 15, participant_left_timeout: 0, language: 'english', enableVideo: true, enableAudio: true, }, }; const conversation = await tavusClient.createConversation(conversationRequest); expect(conversation.conversationId).toBe('c123456'); expect(conversation.roomUrl).toBe('https://tavus.daily.co/c123456'); expect(conversation.isActive).toBe(true); expect(conversation.replicaId).toBe('rf4703150052'); expect(conversation.personaId).toBe('p48fdf065d6b'); expect(mockFetch).toHaveBeenCalledWith( 'https://tavusapi.com/v2/conversations', expect.objectContaining({ method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'test-api-key-123', }, body: JSON.stringify({ replica_id: 'rf4703150052', persona_id: 'p48fdf065d6b', properties: { enable_recording: true, aws_assume_role_arn: "arn:aws:iam::803663093034:role/CVIRecordingRole", recording_s3_bucket_region: "eu-north-1", recording_s3_bucket_name: "buzztrail-tavus-main", max_call_duration: 15, participant_left_timeout: 0, language: 'english', enableVideo: true, enableAudio: true, }, }), }) ); }); it('should handle conversation creation errors', async () => { mockFetch.mockResolvedValueOnce({ ok: false, status: 400, statusText: 'Bad Request', json: async () => ({ error: 'Invalid replica or persona ID' }), }); const conversationRequest: ConversationRequest = { replicaId: 'invalid-replica', personaId: 'invalid-persona', }; // The error handling is working correctly - it should throw an error await expect(tavusClient.createConversation(conversationRequest)).rejects.toThrow(); }); it('should validate conversation request parameters', async () => { const invalidRequest = { replicaId: '', personaId: '', } as ConversationRequest; // Mock a failed response to trigger validation error mockFetch.mockResolvedValueOnce({ ok: false, status: 400, json: async () => ({ error: 'replicaId is required and must be a non-empty string' }), }); // The validation should throw an error for empty strings await expect(tavusClient.createConversation(invalidRequest)).rejects.toThrow(); }); }); describe('WebRTC Connection', () => { beforeEach(async () => { // Mock successful initialization mockFetch.mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({ replicas: [] }), }); await tavusClient.initialize(); }); it('should connect to WebRTC room and return video stream', async () => { const roomUrl = 'https://tavus.daily.co/c123456'; const accessToken = 'test-access-token'; // Mock successful Daily.js connection mockDailyCall.on.mockImplementation((event: string, callback: () => void) => { if (event === 'joined-meeting') { // Simulate successful join immediately callback(); } }); // Mock participants with video track mockDailyCall.participants.mockReturnValue({ 'remote-participant': { owner: true, video: true, videoTrack: mockMediaStreamTrack, }, }); const videoStream = await tavusClient.connectToWebRTCRoom(roomUrl, accessToken); expect(videoStream).toBeDefined(); expect(mockDailyIframe.createFrame).toHaveBeenCalled(); expect(mockDailyCall.join).toHaveBeenCalledWith({ url: roomUrl, token: accessToken, }); }); it('should handle WebRTC connection errors', async () => { const roomUrl = 'https://tavus.daily.co/c123456'; // Mock Daily.js error mockDailyCall.join.mockRejectedValue(new Error('Failed to join meeting')); // Should throw error instead of fallback await expect(tavusClient.connectToWebRTCRoom(roomUrl)).rejects.toThrow('Failed to join meeting'); }); it('should validate room URL parameter', async () => { // Should throw error for invalid room URL await expect(tavusClient.connectToWebRTCRoom('')).rejects.toThrow('Room URL is required for WebRTC connection'); await expect(tavusClient.connectToWebRTCRoom(null as any)).rejects.toThrow('Room URL is required for WebRTC connection'); }); }); describe('Conversation Management', () => { beforeEach(async () => { // Mock successful initialization mockFetch.mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({ replicas: [] }), }); await tavusClient.initialize(); }); it('should get conversation details', async () => { const mockConversation = { conversation_id: 'c123456', conversation_url: 'https://tavus.daily.co/c123456', status: 'active', replica_id: 'rf4703150052', persona_id: 'p48fdf065d6b', created_at: '2024-01-01T00:00:00Z', updated_at: '2024-01-01T00:00:00Z', }; mockFetch.mockResolvedValueOnce({ ok: true, status: 200, json: async () => mockConversation, }); const conversation = await tavusClient.getConversation('c123456'); expect(conversation.conversationId).toBe('c123456'); expect(conversation.roomUrl).toBe('https://tavus.daily.co/c123456'); expect(conversation.isActive).toBe(true); expect(mockFetch).toHaveBeenCalledWith( 'https://tavusapi.com/v2/conversations/c123456', expect.objectContaining({ method: 'GET', headers: { 'Content-Type': 'application/json', 'x-api-key': 'test-api-key-123', }, }) ); }); it('should end conversation successfully', async () => { mockFetch.mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({}), }); await tavusClient.endConversation('c123456'); expect(mockFetch).toHaveBeenCalledWith( 'https://tavusapi.com/v2/conversations/c123456', expect.objectContaining({ method: 'DELETE', headers: { 'Content-Type': 'application/json', 'x-api-key': 'test-api-key-123', }, }) ); }); it('should get existing conversations for cleanup', async () => { const mockConversations = [ { conversation_id: 'c123456', conversation_url: 'https://tavus.daily.co/c123456', status: 'active', }, { conversation_id: 'c789012', conversation_url: 'https://tavus.daily.co/c789012', status: 'ended', }, ]; mockFetch.mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({ conversations: mockConversations }), }); const conversations = await tavusClient.getConversations(); expect(conversations).toHaveLength(2); expect(conversations[0]?.conversationId).toBe('c123456'); expect(conversations[1]?.conversationId).toBe('c789012'); expect(mockFetch).toHaveBeenCalledWith( 'https://tavusapi.com/v2/conversations', expect.objectContaining({ method: 'GET', headers: { 'Content-Type': 'application/json', 'x-api-key': 'test-api-key-123', }, }) ); }); }); });