|
| 1 | +import { render, screen, fireEvent, act } from '@testing-library/react'; |
| 2 | +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; |
| 3 | +import { OfflineBanner } from '@/components/ui/offline-banner'; |
| 4 | +import { useOfflineStore } from '@/lib/store/offlineStore'; |
| 5 | + |
| 6 | +// Control the browser-detected connectivity that feeds the store. |
| 7 | +let mockOnline = false; |
| 8 | +jest.mock('@/lib/hooks/useOnlineStatus', () => ({ |
| 9 | + useOnlineStatus: () => mockOnline, |
| 10 | +})); |
| 11 | + |
| 12 | +function renderBanner() { |
| 13 | + const client = new QueryClient({ |
| 14 | + defaultOptions: { queries: { retry: false } }, |
| 15 | + }); |
| 16 | + jest.spyOn(client, 'refetchQueries').mockResolvedValue(undefined); |
| 17 | + const utils = render( |
| 18 | + <QueryClientProvider client={client}> |
| 19 | + <OfflineBanner /> |
| 20 | + </QueryClientProvider> |
| 21 | + ); |
| 22 | + return { client, ...utils }; |
| 23 | +} |
| 24 | + |
| 25 | +const bannerText = () => screen.queryByText(/you are offline/i); |
| 26 | + |
| 27 | +beforeEach(() => { |
| 28 | + mockOnline = false; |
| 29 | + act(() => { |
| 30 | + useOfflineStore.setState({ isOnline: true, dismissed: false }); |
| 31 | + }); |
| 32 | +}); |
| 33 | + |
| 34 | +describe('OfflineBanner', () => { |
| 35 | + it('reflects useOfflineStore connectivity state', () => { |
| 36 | + renderBanner(); |
| 37 | + // Store transitioned to offline on mount -> banner visible. |
| 38 | + expect(bannerText()).toBeInTheDocument(); |
| 39 | + |
| 40 | + act(() => { |
| 41 | + useOfflineStore.getState().setIsOnline(true); |
| 42 | + }); |
| 43 | + // Back online per the store -> banner hidden. |
| 44 | + expect(bannerText()).not.toBeInTheDocument(); |
| 45 | + }); |
| 46 | + |
| 47 | + it('is dismissible and reappears on the next offline transition', () => { |
| 48 | + renderBanner(); |
| 49 | + expect(bannerText()).toBeInTheDocument(); |
| 50 | + |
| 51 | + fireEvent.click( |
| 52 | + screen.getByRole('button', { name: /dismiss offline notification/i }) |
| 53 | + ); |
| 54 | + expect(bannerText()).not.toBeInTheDocument(); |
| 55 | + |
| 56 | + // Reconnect, then drop offline again: dismissal must reset so the banner |
| 57 | + // comes back instead of staying hidden forever. |
| 58 | + act(() => { |
| 59 | + useOfflineStore.getState().setIsOnline(true); |
| 60 | + }); |
| 61 | + act(() => { |
| 62 | + useOfflineStore.getState().setIsOnline(false); |
| 63 | + }); |
| 64 | + expect(bannerText()).toBeInTheDocument(); |
| 65 | + }); |
| 66 | + |
| 67 | + it('re-fetches failed data when Retry is clicked', () => { |
| 68 | + const { client } = renderBanner(); |
| 69 | + fireEvent.click(screen.getByRole('button', { name: /retry/i })); |
| 70 | + expect(client.refetchQueries).toHaveBeenCalled(); |
| 71 | + }); |
| 72 | +}); |
0 commit comments