import { render } from '@testing-library/react'; import { describe, it, expect, vi, beforeEach } from 'vitest'; import { BrowserRouter, MemoryRouter } from 'react-router-dom'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { ProtectedRoute } from './ProtectedRoute'; // Mock useAuthStore const mockIsAuthenticated = vi.fn(() => false); vi.mock('@/stores/auth', () => ({ useAuthStore: () => ({ isAuthenticated: mockIsAuthenticated(), }), })); const createTestQueryClient = () => new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false }, }, }); const TestWrapper = ({ children }: { children: React.ReactNode }) => { const queryClient = createTestQueryClient(); return ( {children} ); }; describe('ProtectedRoute Component', () => { beforeEach(() => { vi.clearAllMocks(); }); it('renders children when user is authenticated', () => { mockIsAuthenticated.mockReturnValue(true); const { getByText } = render(
Protected Content
); expect(getByText('Protected Content')).toBeInTheDocument(); }); it('redirects to login when user is not authenticated', () => { mockIsAuthenticated.mockReturnValue(false); render(
Protected Content
); // Le composant Navigate devrait rediriger vers /login // On vérifie que le contenu protégé n'est pas visible const protectedContent = document.querySelector('div'); expect(protectedContent?.textContent).not.toBe('Protected Content'); }); it('uses replace navigation when redirecting', () => { mockIsAuthenticated.mockReturnValue(false); const { container } = render(
Protected Content
); // Le composant Navigate devrait être présent avec replace expect(container).toBeInTheDocument(); }); it('renders multiple children correctly when authenticated', () => { mockIsAuthenticated.mockReturnValue(true); const { getByText } = render(
Child 1
Child 2
); expect(getByText('Child 1')).toBeInTheDocument(); expect(getByText('Child 2')).toBeInTheDocument(); }); it('handles empty children gracefully', () => { mockIsAuthenticated.mockReturnValue(true); const { container } = render( {null} ); expect(container).toBeInTheDocument(); }); });