|
| 1 | +import { render, screen, waitFor } from '@testing-library/react'; |
| 2 | +import { vi } from 'vitest'; |
| 3 | +import ActivityFeed from './ActivityFeed'; |
| 4 | + |
| 5 | +// 1. Capture the original global fetch to prevent side effects |
| 6 | +const originalFetch = global.fetch; |
| 7 | + |
| 8 | +const mockEvents = [ |
| 9 | + { |
| 10 | + id: '12345', |
| 11 | + type: 'PushEvent', |
| 12 | + created_at: new Date().toISOString(), |
| 13 | + repo: { name: 'GitMetricsLab/github_tracker' } |
| 14 | + } |
| 15 | +]; |
| 16 | + |
| 17 | +// Helper to generate a full Response-like object to satisfy TypeScript |
| 18 | +const createMockResponse = (data: any): Partial<Response> => ({ |
| 19 | + ok: true, |
| 20 | + status: 200, |
| 21 | + statusText: 'OK', |
| 22 | + json: async () => data, |
| 23 | +}); |
| 24 | + |
| 25 | +describe('ActivityFeed Component', () => { |
| 26 | + beforeAll(() => { |
| 27 | + // Mock fetch before the suite runs |
| 28 | + global.fetch = vi.fn(); |
| 29 | + }); |
| 30 | + |
| 31 | + afterEach(() => { |
| 32 | + // Clear mock history between individual tests |
| 33 | + vi.clearAllMocks(); |
| 34 | + }); |
| 35 | + |
| 36 | + afterAll(() => { |
| 37 | + // 2. Restore original fetch after the suite finishes to prevent leaks |
| 38 | + global.fetch = originalFetch; |
| 39 | + }); |
| 40 | + |
| 41 | + it('displays the loading state initially', () => { |
| 42 | + vi.mocked(global.fetch).mockResolvedValueOnce(createMockResponse([]) as Response); |
| 43 | + |
| 44 | + render(<ActivityFeed username="testuser" />); |
| 45 | + |
| 46 | + expect(screen.getByText('Loading...')).toBeInTheDocument(); |
| 47 | + }); |
| 48 | + |
| 49 | + it('renders activity events after successful fetch', async () => { |
| 50 | + vi.mocked(global.fetch).mockResolvedValueOnce(createMockResponse(mockEvents) as Response); |
| 51 | + |
| 52 | + render(<ActivityFeed username="testuser" />); |
| 53 | + |
| 54 | + await waitFor(() => { |
| 55 | + expect(screen.queryByText('Loading...')).not.toBeInTheDocument(); |
| 56 | + }); |
| 57 | + |
| 58 | + expect(screen.getByText('🚀 Commit pushed')).toBeInTheDocument(); |
| 59 | + expect(screen.getByText(/GitMetricsLab\/github_tracker/)).toBeInTheDocument(); |
| 60 | + }); |
| 61 | + |
| 62 | + it('displays a fallback message when no activity is found', async () => { |
| 63 | + vi.mocked(global.fetch).mockResolvedValueOnce(createMockResponse([]) as Response); |
| 64 | + |
| 65 | + render(<ActivityFeed username="testuser" />); |
| 66 | + |
| 67 | + await waitFor(() => { |
| 68 | + expect(screen.getByText('No activity found')).toBeInTheDocument(); |
| 69 | + }); |
| 70 | + }); |
| 71 | +}); |
0 commit comments