| import { describe, it, expect, beforeEach } from 'vitest'; |
| import { render, screen } from '@testing-library/react'; |
| import RoleBasedControl from './PermissionControl'; |
| |
| describe('RoleBasedControl 组件', () => { |
| beforeEach(() => { |
| window.localStorage.clear(); |
| }); |
| |
| it('用户没有所需角色时不应该渲染内容', () => { |
| // 模拟普通用户 |
| window.localStorage.setItem('user', JSON.stringify({ role: 'user' })); |
| |
| const { container } = render( |
| <RoleBasedControl allowedRoles={['admin']}> |
| <div>管理员内容</div> |
| </RoleBasedControl> |
| ); |
| |
| // 不应该渲染任何内容 |
| expect(container.firstChild).toBeNull(); |
| }); |
| |
| it('用户有所需角色时应该渲染内容', () => { |
| // 模拟管理员 |
| window.localStorage.setItem('user', JSON.stringify({ role: 'admin' })); |
| |
| render( |
| <RoleBasedControl allowedRoles={['admin']}> |
| <div>管理员内容</div> |
| </RoleBasedControl> |
| ); |
| |
| // 应该看到管理员内容 |
| expect(screen.getByText('管理员内容')).toBeInTheDocument(); |
| }); |
| |
| it('多个允许的角色中有一个匹配时应该渲染内容', () => { |
| // 模拟版主 |
| window.localStorage.setItem('user', JSON.stringify({ role: 'moderator' })); |
| |
| render( |
| <RoleBasedControl allowedRoles={['admin', 'moderator']}> |
| <div>特权内容</div> |
| </RoleBasedControl> |
| ); |
| |
| // 应该看到特权内容 |
| expect(screen.getByText('特权内容')).toBeInTheDocument(); |
| }); |
| }); |