/** * Tests for TavusClient Raven-0 integration * * Tests page analysis and perception analysis functionality */ import { TavusClient, TavusConfig } from '../shared/utils/api-clients/tavus-client'; // Mock DOM environment for testing const mockDocument = { title: 'Test Page', body: { textContent: 'This is a test page with some content for testing purposes.', }, querySelector: jest.fn(), querySelectorAll: jest.fn(), }; const mockWindow = { location: { href: 'https://example.com/test-page', }, }; // Mock DOM elements const mockElement = { getBoundingClientRect: () => ({ left: 10, top: 20, width: 100, height: 50 }), textContent: 'Test Button', getAttribute: jest.fn(), closest: jest.fn(), }; const mockAnchorElement = { ...mockElement, href: 'https://example.com/link', textContent: 'Test Link', }; const mockButtonElement = { ...mockElement, textContent: 'Submit', onclick: null, }; const mockInputElement = { ...mockElement, value: 'test input', placeholder: 'Enter text', type: 'text', }; describe('TavusClient Raven-0 Integration', () => { let tavusClient: TavusClient; let originalDocument: any; let originalWindow: any; beforeEach(() => { // Mock fetch for API calls global.fetch = jest.fn().mockResolvedValue({ ok: true, status: 200, json: async () => ({ replicas: [] }), }); // Store original globals originalDocument = global.document; originalWindow = global.window; // Reset mock document state mockDocument.title = 'Test Page'; mockDocument.body = { textContent: 'This is a test page with some content for testing purposes.', }; mockWindow.location.href = 'https://example.com/test-page'; // Mock DOM environment global.document = mockDocument as any; global.window = mockWindow as any; // Reset mocks jest.clearAllMocks(); }); afterEach(() => { // Restore original globals global.document = originalDocument; global.window = originalWindow; }); beforeAll(async () => { tavusClient = new TavusClient({ debug: true, }); await tavusClient.initialize(); }); describe('Page Analysis', () => { it('should analyze page with basic information', async () => { // Mock basic page structure (mockDocument.querySelector as jest.Mock).mockReturnValue(null); (mockDocument.querySelectorAll as jest.Mock).mockReturnValue([]); const analysis = await tavusClient.analyzePage(); expect(analysis).toEqual({ title: 'Test Page', description: 'No description available', interactiveElements: [], navigationOptions: [], contentSummary: 'This is a test page with some content for testing purposes.', userIntent: 'browsing', pageType: 'other', }); }); it('should classify e-commerce pages correctly', async () => { // Mock e-commerce page mockDocument.title = 'Shop - Buy Products Online'; mockWindow.location.href = 'https://shop.example.com/product/123'; (mockDocument.body as any).textContent = 'Add to cart Buy now $99.99'; const analysis = await tavusClient.analyzePage(); expect(analysis.pageType).toBe('e-commerce'); expect(analysis.userIntent).toBe('purchasing'); }); it('should classify SaaS pages correctly', async () => { // Mock SaaS page mockDocument.title = 'Dashboard - MyApp Platform'; mockWindow.location.href = 'https://app.example.com/dashboard'; (mockDocument.body as any).textContent = 'Login Sign up Dashboard'; const analysis = await tavusClient.analyzePage(); expect(analysis.pageType).toBe('saas'); }); it('should classify blog pages correctly', async () => { // Mock blog page mockDocument.title = 'How to Build a Blog - Tutorial'; mockWindow.location.href = 'https://blog.example.com/article/123'; (mockDocument.querySelector as jest.Mock).mockReturnValue(mockElement); // Mock article element const analysis = await tavusClient.analyzePage(); expect(analysis.pageType).toBe('blog'); }); it('should classify help desk pages correctly', async () => { // Mock help desk page mockDocument.title = 'Help & Support - Contact Us'; mockWindow.location.href = 'https://help.example.com/support'; (mockDocument.body as any).textContent = 'Help Support FAQ Contact us'; const analysis = await tavusClient.analyzePage(); expect(analysis.pageType).toBe('help-desk'); expect(analysis.userIntent).toBe('seeking_support'); }); it('should extract interactive elements', async () => { // Create mock elements with proper structure const mockButton = { tagName: 'BUTTON', textContent: 'Submit', title: '', onclick: null, getBoundingClientRect: () => ({ left: 10, top: 20, width: 100, height: 50 }), getAttribute: () => null, }; const mockAnchor = { tagName: 'A', textContent: 'Test Link', title: '', href: 'https://example.com/link', getBoundingClientRect: () => ({ left: 50, top: 30, width: 80, height: 30 }), getAttribute: () => null, }; const mockInput = { tagName: 'INPUT', textContent: '', title: '', value: 'test input', placeholder: 'Enter text', type: 'text', getBoundingClientRect: () => ({ left: 20, top: 40, width: 150, height: 25 }), getAttribute: () => null, }; // Mock querySelectorAll to return different elements for different selectors (mockDocument.querySelectorAll as jest.Mock).mockImplementation((selector: string) => { if (selector === 'button') return [mockButton]; if (selector === 'a[href]') return [mockAnchor]; if (selector === 'input[type="submit"]') return []; if (selector === 'input[type="button"]') return []; if (selector === 'select') return []; if (selector === 'textarea') return []; if (selector === 'form') return []; if (selector === '[role="button"]') return []; if (selector === '[role="link"]') return []; if (selector === '[onclick]') return []; return []; }); const analysis = await tavusClient.analyzePage(); expect(analysis.interactiveElements.length).toBeGreaterThan(0); expect(analysis.interactiveElements[0]).toHaveProperty('type'); expect(analysis.interactiveElements[0]).toHaveProperty('text'); expect(analysis.interactiveElements[0]).toHaveProperty('position'); expect(analysis.interactiveElements[0]).toHaveProperty('visible'); }); it('should extract navigation options', async () => { // Create mock navigation element with proper structure const mockNavElement = { tagName: 'A', textContent: 'Test Link', title: '', href: 'https://example.com/nav-link', getBoundingClientRect: () => ({ left: 10, top: 20, width: 100, height: 50 }), getAttribute: () => null, closest: jest.fn().mockReturnValue({ tagName: 'NAV' }), // Mock nav parent }; // Mock querySelectorAll to return navigation elements (mockDocument.querySelectorAll as jest.Mock).mockImplementation((selector: string) => { if (selector === 'nav a') return [mockNavElement]; if (selector === 'header a') return []; if (selector === '.navigation a') return []; if (selector === '.nav a') return []; if (selector === '.menu a') return []; if (selector === '.breadcrumb a') return []; return []; }); const analysis = await tavusClient.analyzePage(); expect(analysis.navigationOptions.length).toBeGreaterThan(0); expect(analysis.navigationOptions[0]).toHaveProperty('url'); expect(analysis.navigationOptions[0]).toHaveProperty('text'); expect(analysis.navigationOptions[0]).toHaveProperty('primary'); }); it('should handle non-browser environment gracefully', async () => { // Remove document to simulate non-browser environment global.document = undefined as any; const analysis = await tavusClient.analyzePage(); expect(analysis.title).toBe('Unknown Page'); expect(analysis.description).toBe('Page analysis not available in non-browser environment'); expect(analysis.interactiveElements).toEqual([]); expect(analysis.navigationOptions).toEqual([]); expect(analysis.contentSummary).toBe('No content available'); expect(analysis.userIntent).toBe('unknown'); expect(analysis.pageType).toBe('other'); }); }); describe('Perception Analysis', () => { it('should generate perception analysis from page analysis', async () => { // Mock positive content mockDocument.title = 'Amazing Success Story - Great Results'; (mockDocument.body as any).textContent = 'This is a fantastic success story with excellent results.'; const perception = await tavusClient.getPerceptionAnalysis(); expect(perception).toHaveProperty('sentiment'); expect(perception).toHaveProperty('engagementLevel'); expect(perception).toHaveProperty('recommendedBehavior'); expect(perception).toHaveProperty('insights'); expect(perception).toHaveProperty('confidence'); expect(typeof perception.confidence).toBe('number'); expect(perception.confidence).toBeGreaterThanOrEqual(0); expect(perception.confidence).toBeLessThanOrEqual(1); }); it('should detect positive sentiment', async () => { // Mock positive content mockDocument.title = 'Amazing Success - Great Results'; (mockDocument.body as any).textContent = 'This is a fantastic success story with excellent results and wonderful outcomes.'; const perception = await tavusClient.getPerceptionAnalysis(); expect(perception.sentiment).toBe('positive'); }); it('should detect negative sentiment', async () => { // Mock negative content with more negative words mockDocument.title = 'Error - Problem Report - Terrible Issue'; (mockDocument.body as any).textContent = 'This is a terrible problem with awful results and broken functionality. The system is completely failed and everything is wrong. This is a bad situation with horrible outcomes.'; const perception = await tavusClient.getPerceptionAnalysis(); expect(perception.sentiment).toBe('negative'); }); it('should detect neutral sentiment', async () => { // Mock neutral content mockDocument.title = 'Information Page'; (mockDocument.body as any).textContent = 'This is a standard information page with basic content.'; const perception = await tavusClient.getPerceptionAnalysis(); expect(perception.sentiment).toBe('neutral'); }); it('should calculate engagement levels correctly', async () => { // Mock high-engagement page mockDocument.title = 'Product Page - Buy Now'; mockWindow.location.href = 'https://shop.example.com/product/123'; (mockDocument.body as any).textContent = 'Add to cart Buy now $99.99'; const mockElements = Array(20).fill(mockButtonElement); (mockDocument.querySelectorAll as jest.Mock).mockReturnValue(mockElements); const perception = await tavusClient.getPerceptionAnalysis(); expect(['low', 'medium', 'high']).toContain(perception.engagementLevel); }); it('should generate appropriate recommended behaviors', async () => { // Mock e-commerce page mockDocument.title = 'Shop - Buy Products'; mockWindow.location.href = 'https://shop.example.com/product/123'; (mockDocument.body as any).textContent = 'Add to cart Buy now'; const perception = await tavusClient.getPerceptionAnalysis(); expect(perception.recommendedBehavior).toContain('Product-focused assistance'); expect(perception.recommendedBehavior).toContain('Purchase guidance'); }); it('should generate insights based on page analysis', async () => { // Mock SaaS page mockDocument.title = 'Dashboard - MyApp'; mockWindow.location.href = 'https://app.example.com/dashboard'; (mockDocument.body as any).textContent = 'Dashboard Login Sign up'; const perception = await tavusClient.getPerceptionAnalysis(); expect(Array.isArray(perception.insights)).toBe(true); expect(perception.insights.length).toBeGreaterThan(0); expect(typeof perception.insights[0]).toBe('string'); }); it('should calculate confidence scores', async () => { // Mock rich content page mockDocument.title = 'Detailed Tutorial - Learn Everything'; mockWindow.location.href = 'https://learn.example.com/tutorial'; (mockDocument.body as any).textContent = 'This is a very detailed tutorial with lots of content and information for learning purposes. It contains many paragraphs of educational material that will help users understand the concepts thoroughly.'; const mockElements = Array(10).fill(mockButtonElement); (mockDocument.querySelectorAll as jest.Mock).mockReturnValue(mockElements); const perception = await tavusClient.getPerceptionAnalysis(); expect(perception.confidence).toBeGreaterThan(0.5); // Should be higher for rich content expect(perception.confidence).toBeLessThanOrEqual(1.0); }); it('should handle errors gracefully', async () => { // Mock error condition global.document = undefined as any; const perception = await tavusClient.getPerceptionAnalysis(); expect(perception).toHaveProperty('sentiment'); expect(perception).toHaveProperty('engagementLevel'); expect(perception).toHaveProperty('recommendedBehavior'); expect(perception).toHaveProperty('insights'); expect(perception).toHaveProperty('confidence'); }); }); describe('Error Handling', () => { it('should throw error if not initialized', async () => { const uninitializedClient = new TavusClient({ debug: true }); await expect(uninitializedClient.analyzePage()).rejects.toThrow( 'TavusClient must be initialized before analyzing pages' ); await expect(uninitializedClient.getPerceptionAnalysis()).rejects.toThrow( 'TavusClient must be initialized before getting perception analysis' ); }); it('should handle DOM errors gracefully', async () => { // Reset document state for this test mockDocument.title = 'Test Page'; mockDocument.body = { textContent: 'This is a test page with some content for testing purposes.', }; // Mock DOM errors (mockDocument.querySelector as jest.Mock).mockImplementation(() => { throw new Error('DOM Error'); }); const analysis = await tavusClient.analyzePage(); expect(analysis).toBeDefined(); expect(analysis.title).toBe('Test Page'); }); }); });