// src/components/AdminRoute.test.tsx import React from 'react'; import { render, screen } from '@testing-library/react'; import { describe, it, expect } from 'vitest'; import { MemoryRouter, Routes, Route } from 'react-router-dom'; import { AdminRoute } from './AdminRoute'; import type { Profile } from '../types'; import { createMockProfile } from '../tests/utils/mockFactories'; // Unmock the component to test the real implementation vi.unmock('./AdminRoute'); const AdminContent = () =>
Admin Page Content
; const HomePage = () =>
Home Page
; const renderWithRouter = (profile: Profile | null, initialPath: string) => { render( } /> }> } /> , ); }; describe('AdminRoute', () => { it('should render the admin content when user has admin role', () => { const adminProfile: Profile = createMockProfile({ role: 'admin' }); renderWithRouter(adminProfile, '/admin'); expect(screen.getByText('Admin Page Content')).toBeInTheDocument(); expect(screen.queryByText('Home Page')).not.toBeInTheDocument(); }); it('should redirect to home page when user does not have admin role', () => { const userProfile: Profile = createMockProfile({ role: 'user' }); renderWithRouter(userProfile, '/admin'); // The user is redirected, so we should see the home page content expect(screen.getByText('Home Page')).toBeInTheDocument(); expect(screen.queryByText('Admin Page Content')).not.toBeInTheDocument(); }); it('should redirect to home page when profile is null', () => { renderWithRouter(null, '/admin'); // The user is redirected, so we should see the home page content expect(screen.getByText('Home Page')).toBeInTheDocument(); expect(screen.queryByText('Admin Page Content')).not.toBeInTheDocument(); }); });