5dc53f57cc
- 新增系统监控模块(在线用户、定时任务、数据监控、服务器监控、缓存监控) - 新增部门管理占位页面 - 路由注册新增模块与懒加载 - DefaultLayout 侧边菜单与布局优化 - 新增前端单元测试与后端 RoleUpdateRequest 测试
79 lines
2.6 KiB
TypeScript
79 lines
2.6 KiB
TypeScript
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(
|
|
<PermissionGuard permission="system:user:list">
|
|
<div>Protected Content</div>
|
|
</PermissionGuard>
|
|
)
|
|
expect(screen.getByText('Protected Content')).toBeInTheDocument()
|
|
})
|
|
|
|
it('should render fallback when user lacks permission', () => {
|
|
mockUsePermissionStore.mockImplementation((selector: any) =>
|
|
selector({ hasPermission: () => false, hasRole: () => false })
|
|
)
|
|
render(
|
|
<PermissionGuard permission="system:user:list" fallback={<div>No Access</div>}>
|
|
<div>Protected Content</div>
|
|
</PermissionGuard>
|
|
)
|
|
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(
|
|
<PermissionGuard permission="system:user:list">
|
|
<div>Protected Content</div>
|
|
</PermissionGuard>
|
|
)
|
|
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(
|
|
<PermissionGuard role="admin" type="role">
|
|
<div>Admin Content</div>
|
|
</PermissionGuard>
|
|
)
|
|
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(
|
|
<PermissionGuard>
|
|
<div>Always Visible</div>
|
|
</PermissionGuard>
|
|
)
|
|
expect(screen.getByText('Always Visible')).toBeInTheDocument()
|
|
})
|
|
})
|