import { describe, it, expect, vi, beforeEach } from 'vitest' import { render, screen } from '@testing-library/react' import PermissionGuard from '@/components/PermissionGuard' vi.mock('@/stores/usePermissionStore', () => ({ usePermissionStore: vi.fn(), })) import { usePermissionStore } from '@/stores/usePermissionStore' const mockUsePermissionStore = vi.mocked(usePermissionStore) describe('PermissionGuard', () => { beforeEach(() => { vi.clearAllMocks() }) it('should render children when user has permission', () => { mockUsePermissionStore.mockImplementation((selector: any) => selector({ hasPermission: (p: string) => p === 'system:user:list', hasRole: () => false }) ) render(
Protected Content
) expect(screen.getByText('Protected Content')).toBeInTheDocument() }) it('should render fallback when user lacks permission', () => { mockUsePermissionStore.mockImplementation((selector: any) => selector({ hasPermission: () => false, hasRole: () => false }) ) render( No Access}>
Protected Content
) expect(screen.queryByText('Protected Content')).not.toBeInTheDocument() expect(screen.getByText('No Access')).toBeInTheDocument() }) it('should render null fallback by default when no permission', () => { mockUsePermissionStore.mockImplementation((selector: any) => selector({ hasPermission: () => false, hasRole: () => false }) ) const { container } = render(
Protected Content
) expect(container.innerHTML).toBe('') }) it('should check role when type is role', () => { mockUsePermissionStore.mockImplementation((selector: any) => selector({ hasPermission: () => false, hasRole: (r: string) => r === 'admin' }) ) render(
Admin Content
) expect(screen.getByText('Admin Content')).toBeInTheDocument() }) it('should render children when no permission or role specified', () => { mockUsePermissionStore.mockImplementation((selector: any) => selector({ hasPermission: () => false, hasRole: () => false }) ) render(
Always Visible
) expect(screen.getByText('Always Visible')).toBeInTheDocument() }) })