import { describe, expect, it, vi } from 'vitest'; import { render, screen } from '@testing-library/react'; import { RequireRole } from './RequireRole'; import * as useAuthModule from '../hooks/useAuth'; function mockAuth(user: { roles: string[] } | null) { vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({ user: user as never, loading: false, login: vi.fn(), logout: vi.fn(), setUser: vi.fn(), }); } describe('', () => { it('renders children when the user has the required role', () => { mockAuth({ roles: ['Admin'] }); render(
Admin-only content
, ); expect(screen.getByText('Admin-only content')).toBeInTheDocument(); }); it('renders a 403 when the user is missing the required role', () => { mockAuth({ roles: ['User'] }); render(
Admin-only content
, ); expect(screen.queryByText('Admin-only content')).not.toBeInTheDocument(); expect(screen.getByText('403')).toBeInTheDocument(); }); it('renders a 403 when the user is null (unauthenticated edge)', () => { mockAuth(null); render(
Admin-only content
, ); expect(screen.getByText('403')).toBeInTheDocument(); }); });