All files / src/components/features/admin/monitoring/DatabasePerformance DatabasePerformance.test.tsx

0% Statements 0/275
100% Branches 0/0
0% Functions 0/1
0% Lines 0/275

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
import React from 'react';
import { render, screen, within } from '@testing-library/react';
import { DatabasePerformance, type DatabasePerformanceProps } from './index';

// Mock data
const mockSlowQueries = [
  {
    id: 'query-1',
    name: 'findManyProducts',
    operation: 'findMany',
    tableName: 'product',
    duration: 1250,
    rowCount: 5000,
    success: true,
    errorType: null,
    timestamp: new Date('2024-01-15T10:30:00Z'),
  },
  {
    id: 'query-2',
    name: 'aggregateOrders',
    operation: 'aggregate',
    tableName: 'order',
    duration: 890,
    rowCount: null,
    success: false,
    errorType: 'TimeoutError',
    timestamp: new Date('2024-01-15T10:25:00Z'),
  },
];

const mockQueryStats = [
  { tableName: 'product', avgDuration: 45.2, totalCalls: 1250, slowCount: 5 },
  { tableName: 'order', avgDuration: 82.5, totalCalls: 780, slowCount: 12 },
  { tableName: 'user', avgDuration: 23.8, totalCalls: 2100, slowCount: 0 },
];

const mockOperationBreakdown = {
  findMany: 4500,
  findFirst: 2100,
  create: 999,
  update: 650,
};

const defaultProps: DatabasePerformanceProps = {
  totalQueries: 11500,
  avgDuration: 67.4,
  slowQueries: mockSlowQueries,
  queryStats: mockQueryStats,
  operationBreakdown: mockOperationBreakdown,
  slowThreshold: 500,
  timePeriod: '24h',
};

describe('DatabasePerformance', () => {
  describe('Rendering', () => {
    it('renders without crashing', () => {
      render(<DatabasePerformance {...defaultProps} />);
      expect(screen.getByTestId('database-performance')).toBeInTheDocument();
    });

    it('displays total queries count', () => {
      render(<DatabasePerformance {...defaultProps} />);
      expect(screen.getByText('11,500')).toBeInTheDocument();
    });

    it('displays average duration', () => {
      render(<DatabasePerformance {...defaultProps} />);
      expect(screen.getByText('67ms')).toBeInTheDocument();
    });

    it('displays slow queries count in summary card', () => {
      render(<DatabasePerformance {...defaultProps} />);
      // 2 slow queries in the mock data
      const summaryCards = screen.getAllByText('2');
      expect(summaryCards.length).toBeGreaterThan(0);
    });

    it('displays tables hit count', () => {
      render(<DatabasePerformance {...defaultProps} />);
      // 3 tables in queryStats
      const tablesHitCard = screen.getByText('Tables Hit').closest('div');
      expect(tablesHitCard).toBeInTheDocument();
      if (tablesHitCard) {
        const countElement = within(tablesHitCard).getByText('3');
        expect(countElement).toBeInTheDocument();
      }
    });
  });

  describe('Summary Cards', () => {
    it('shows Total Queries label', () => {
      render(<DatabasePerformance {...defaultProps} />);
      expect(screen.getByText('Total Queries')).toBeInTheDocument();
    });

    it('shows Avg Duration label', () => {
      render(<DatabasePerformance {...defaultProps} />);
      // "Avg Duration" appears in summary card and table header
      const avgDurationLabels = screen.getAllByText('Avg Duration');
      expect(avgDurationLabels.length).toBeGreaterThan(0);
    });

    it('shows Slow Queries label', () => {
      render(<DatabasePerformance {...defaultProps} />);
      // "Slow Queries" appears in summary card and section header
      const slowQueriesLabels = screen.getAllByText(/Slow Queries/);
      expect(slowQueriesLabels.length).toBeGreaterThan(0);
    });

    it('shows Tables Hit label', () => {
      render(<DatabasePerformance {...defaultProps} />);
      expect(screen.getByText('Tables Hit')).toBeInTheDocument();
    });
  });

  describe('Operation Breakdown', () => {
    it('displays all operations', () => {
      render(<DatabasePerformance {...defaultProps} />);
      // findMany appears both in operation breakdown and slow queries
      expect(screen.getAllByText('findMany').length).toBeGreaterThan(0);
      expect(screen.getByText('findFirst')).toBeInTheDocument();
      expect(screen.getByText('create')).toBeInTheDocument();
      expect(screen.getByText('update')).toBeInTheDocument();
    });

    it('displays operation counts', () => {
      render(<DatabasePerformance {...defaultProps} />);
      expect(screen.getByText('4500')).toBeInTheDocument();
      expect(screen.getByText('2100')).toBeInTheDocument();
    });

    it('does not render operation breakdown when empty', () => {
      render(
        <DatabasePerformance {...defaultProps} operationBreakdown={{}} />
      );
      expect(
        screen.queryByText('Operations Breakdown (24h)')
      ).not.toBeInTheDocument();
    });
  });

  describe('Queries by Table', () => {
    it('displays table names', () => {
      render(<DatabasePerformance {...defaultProps} />);
      // Tables appear both in query stats table and slow queries badges
      expect(screen.getAllByText('product').length).toBeGreaterThan(0);
      expect(screen.getAllByText('order').length).toBeGreaterThan(0);
      expect(screen.getByText('user')).toBeInTheDocument();
    });

    it('displays call counts for tables', () => {
      render(<DatabasePerformance {...defaultProps} />);
      expect(screen.getByText('1,250')).toBeInTheDocument();
      expect(screen.getByText('780')).toBeInTheDocument();
      expect(screen.getByText('2,100')).toBeInTheDocument();
    });

    it('shows empty message when no query stats', () => {
      render(<DatabasePerformance {...defaultProps} queryStats={[]} />);
      expect(
        screen.getByText('No table statistics available')
      ).toBeInTheDocument();
    });
  });

  describe('Slow Queries List', () => {
    it('displays slow query names', () => {
      render(<DatabasePerformance {...defaultProps} />);
      expect(screen.getByText('findManyProducts')).toBeInTheDocument();
      expect(screen.getByText('aggregateOrders')).toBeInTheDocument();
    });

    it('displays slow query durations', () => {
      render(<DatabasePerformance {...defaultProps} />);
      expect(screen.getByText('1.25s')).toBeInTheDocument();
      expect(screen.getByText('890ms')).toBeInTheDocument();
    });

    it('displays operation badges', () => {
      render(<DatabasePerformance {...defaultProps} />);
      const findManyBadges = screen.getAllByText('findMany');
      expect(findManyBadges.length).toBeGreaterThan(0);
    });

    it('displays table name badges', () => {
      render(<DatabasePerformance {...defaultProps} />);
      expect(screen.getByText('Table: product')).toBeInTheDocument();
      expect(screen.getByText('Table: order')).toBeInTheDocument();
    });

    it('displays row count when available', () => {
      render(<DatabasePerformance {...defaultProps} />);
      expect(screen.getByText('Rows: 5000')).toBeInTheDocument();
    });

    it('displays failed badge for failed queries', () => {
      render(<DatabasePerformance {...defaultProps} />);
      expect(screen.getByText('Failed')).toBeInTheDocument();
    });

    it('shows empty message when no slow queries', () => {
      render(<DatabasePerformance {...defaultProps} slowQueries={[]} />);
      expect(screen.getByText('No slow queries detected')).toBeInTheDocument();
    });
  });

  describe('Time Period', () => {
    it('displays custom time period in headers', () => {
      render(<DatabasePerformance {...defaultProps} timePeriod="1h" />);
      expect(screen.getByText(/Operations Breakdown \(1h\)/)).toBeInTheDocument();
      expect(screen.getByText(/Queries by Table \(1h\)/)).toBeInTheDocument();
    });

    it('uses default time period when provided', () => {
      render(<DatabasePerformance {...defaultProps} timePeriod="24h" />);
      // Multiple places show 24h, so we check that at least one exists
      expect(screen.getAllByText(/24h/).length).toBeGreaterThan(0);
    });
  });

  describe('Slow Threshold', () => {
    it('displays custom threshold in section header', () => {
      render(<DatabasePerformance {...defaultProps} slowThreshold={200} />);
      expect(screen.getByText(/>\s*200ms/)).toBeInTheDocument();
    });
  });

  describe('Empty State', () => {
    it('handles zero queries gracefully', () => {
      render(
        <DatabasePerformance
          totalQueries={0}
          avgDuration={0}
          slowQueries={[]}
          queryStats={[]}
          operationBreakdown={{}}
        />
      );
      // Multiple elements might have "0", so check with getAllByText
      expect(screen.getAllByText('0').length).toBeGreaterThan(0);
      expect(screen.getByText('<1ms')).toBeInTheDocument();
    });
  });

  describe('Duration Formatting', () => {
    it('formats sub-millisecond durations', () => {
      render(<DatabasePerformance {...defaultProps} avgDuration={0.5} />);
      expect(screen.getByText('<1ms')).toBeInTheDocument();
    });

    it('formats millisecond durations', () => {
      render(<DatabasePerformance {...defaultProps} avgDuration={123} />);
      expect(screen.getByText('123ms')).toBeInTheDocument();
    });

    it('formats second durations', () => {
      render(<DatabasePerformance {...defaultProps} avgDuration={2500} />);
      expect(screen.getByText('2.50s')).toBeInTheDocument();
    });
  });

  describe('Accessibility', () => {
    it('has accessible table structure', () => {
      render(<DatabasePerformance {...defaultProps} />);
      const tables = screen.getAllByRole('table');
      expect(tables.length).toBeGreaterThan(0);
    });

    it('has proper heading hierarchy', () => {
      render(<DatabasePerformance {...defaultProps} />);
      const headings = screen.getAllByRole('heading', { level: 3 });
      expect(headings.length).toBeGreaterThan(0);
    });
  });
});