blob: fb417cde6c83188307476c53415540181ba8f7eb [file] [log] [blame]
ybt02e716d2025-04-15 17:19:32 +08001import { describe, it, expect, beforeEach } from 'vitest';
2import { render, screen } from '@testing-library/react';
3import RoleBasedControl from './PermissionControl';
4
5describe('RoleBasedControl 组件', () => {
6 beforeEach(() => {
7 window.localStorage.clear();
8 });
9
10 it('用户没有所需角色时不应该渲染内容', () => {
11 // 模拟普通用户
12 window.localStorage.setItem('user', JSON.stringify({ role: 'user' }));
13
14 const { container } = render(
15 <RoleBasedControl allowedRoles={['admin']}>
16 <div>管理员内容</div>
17 </RoleBasedControl>
18 );
19
20 // 不应该渲染任何内容
21 expect(container.firstChild).toBeNull();
22 });
23
24 it('用户有所需角色时应该渲染内容', () => {
25 // 模拟管理员
26 window.localStorage.setItem('user', JSON.stringify({ role: 'admin' }));
27
28 render(
29 <RoleBasedControl allowedRoles={['admin']}>
30 <div>管理员内容</div>
31 </RoleBasedControl>
32 );
33
34 // 应该看到管理员内容
35 expect(screen.getByText('管理员内容')).toBeInTheDocument();
36 });
37
38 it('多个允许的角色中有一个匹配时应该渲染内容', () => {
39 // 模拟版主
40 window.localStorage.setItem('user', JSON.stringify({ role: 'moderator' }));
41
42 render(
43 <RoleBasedControl allowedRoles={['admin', 'moderator']}>
44 <div>特权内容</div>
45 </RoleBasedControl>
46 );
47
48 // 应该看到特权内容
49 expect(screen.getByText('特权内容')).toBeInTheDocument();
50 });
51});