|
| 1 | +import React from 'react'; |
| 2 | +import { render, act } from '@testing-library/react'; |
| 3 | +import { describe, it, expect, beforeEach, vi } from 'vitest'; |
| 4 | +import NotificationBell from '../NotificationBell'; |
| 5 | +import { useNotificationStore } from '@/app/store/notificationStore'; |
| 6 | +import { Bell } from 'lucide-react'; |
| 7 | + |
| 8 | +// Mock lucide-react to spy on Bell rendering |
| 9 | +vi.mock('lucide-react', async (importOriginal) => { |
| 10 | + const original = await importOriginal<typeof import('lucide-react')>(); |
| 11 | + return { |
| 12 | + ...original, |
| 13 | + Bell: vi.fn((props) => <original.Bell {...props} />), |
| 14 | + }; |
| 15 | +}); |
| 16 | + |
| 17 | +describe('NotificationBell', () => { |
| 18 | + beforeEach(() => { |
| 19 | + useNotificationStore.setState({ notifications: [] }); |
| 20 | + vi.clearAllMocks(); |
| 21 | + }); |
| 22 | + |
| 23 | + it('renders correctly and has 0 unread initially', () => { |
| 24 | + const { queryByText } = render(<NotificationBell />); |
| 25 | + expect(queryByText('1')).toBeNull(); |
| 26 | + }); |
| 27 | + |
| 28 | + it('renders only once (no extra re-render) when a read notification is added', () => { |
| 29 | + const { queryByText } = render(<NotificationBell />); |
| 30 | + |
| 31 | + // Check initial render count of Bell |
| 32 | + expect(Bell).toHaveBeenCalledTimes(1); |
| 33 | + |
| 34 | + // Add a read notification to the store |
| 35 | + act(() => { |
| 36 | + useNotificationStore.getState().addNotification({ |
| 37 | + id: '1', |
| 38 | + message: 'Read notification', |
| 39 | + type: 'info', |
| 40 | + read: true, |
| 41 | + title: 'Info', |
| 42 | + }); |
| 43 | + }); |
| 44 | + |
| 45 | + // The unread count badge should not be present |
| 46 | + expect(queryByText('1')).toBeNull(); |
| 47 | + |
| 48 | + // Since the notification was already read, the unread count did not change |
| 49 | + // Therefore, the NotificationBell should NOT have re-rendered |
| 50 | + expect(Bell).toHaveBeenCalledTimes(1); |
| 51 | + }); |
| 52 | + |
| 53 | + it('re-renders when an unread notification is added (unread count changes)', () => { |
| 54 | + const { getByText } = render(<NotificationBell />); |
| 55 | + expect(Bell).toHaveBeenCalledTimes(1); |
| 56 | + |
| 57 | + // Add an unread notification to the store |
| 58 | + act(() => { |
| 59 | + useNotificationStore.getState().addNotification({ |
| 60 | + id: '2', |
| 61 | + message: 'Unread notification', |
| 62 | + type: 'info', |
| 63 | + read: false, |
| 64 | + title: 'Info', |
| 65 | + }); |
| 66 | + }); |
| 67 | + |
| 68 | + // The unread count badge should display '1' |
| 69 | + expect(getByText('1')).toBeInTheDocument(); |
| 70 | + |
| 71 | + // Since the unread count changed, the component should re-render |
| 72 | + expect(Bell).toHaveBeenCalledTimes(2); |
| 73 | + }); |
| 74 | +}); |
0 commit comments