ybt | 02e716d | 2025-04-15 17:19:32 +0800 | [diff] [blame^] | 1 | import { describe, it, expect, vi, beforeEach } from 'vitest'; |
| 2 | import { render, screen } from '@testing-library/react'; |
| 3 | import { MemoryRouter } from 'react-router-dom'; |
| 4 | import PermissionRoute from './PermissionRoute'; |
| 5 | |
| 6 | // 模拟 Navigate 组件 |
| 7 | vi.mock('react-router-dom', async () => { |
| 8 | const actual = await vi.importActual('react-router-dom'); |
| 9 | return { |
| 10 | ...actual, |
| 11 | Navigate: () => <div data-testid="navigate-mock">重定向到未授权页面</div>, |
| 12 | }; |
| 13 | }); |
| 14 | |
| 15 | describe('PermissionRoute 组件', () => { |
| 16 | beforeEach(() => { |
| 17 | window.localStorage.clear(); |
| 18 | }); |
| 19 | |
| 20 | it('用户没有所需角色时应该重定向', () => { |
| 21 | // 模拟普通用户 |
| 22 | window.localStorage.setItem('user', JSON.stringify({ role: 'user' })); |
| 23 | |
| 24 | render( |
| 25 | <MemoryRouter> |
| 26 | <PermissionRoute requiredRoles={['admin']}> |
| 27 | <div>管理员内容</div> |
| 28 | </PermissionRoute> |
| 29 | </MemoryRouter> |
| 30 | ); |
| 31 | |
| 32 | // 应该看到重定向组件 |
| 33 | expect(screen.getByTestId('navigate-mock')).toBeInTheDocument(); |
| 34 | }); |
| 35 | |
| 36 | it('用户有所需角色时应该显示子组件', () => { |
| 37 | // 模拟管理员 |
| 38 | window.localStorage.setItem('user', JSON.stringify({ role: 'admin' })); |
| 39 | |
| 40 | render( |
| 41 | <MemoryRouter> |
| 42 | <PermissionRoute requiredRoles={['admin']}> |
| 43 | <div>管理员内容</div> |
| 44 | </PermissionRoute> |
| 45 | </MemoryRouter> |
| 46 | ); |
| 47 | |
| 48 | // 应该看到管理员内容 |
| 49 | expect(screen.getByText('管理员内容')).toBeInTheDocument(); |
| 50 | }); |
| 51 | }); |