| import { describe, it, expect, vi, beforeEach } from 'vitest'; |
| import { render, screen } from '@testing-library/react'; |
| import { MemoryRouter } from 'react-router-dom'; |
| import PermissionRoute from './PermissionRoute'; |
| |
| // 模拟 Navigate 组件 |
| vi.mock('react-router-dom', async () => { |
| const actual = await vi.importActual('react-router-dom'); |
| return { |
| ...actual, |
| Navigate: () => <div data-testid="navigate-mock">重定向到未授权页面</div>, |
| }; |
| }); |
| |
| describe('PermissionRoute 组件', () => { |
| beforeEach(() => { |
| window.localStorage.clear(); |
| }); |
| |
| it('用户没有所需角色时应该重定向', () => { |
| // 模拟普通用户 |
| window.localStorage.setItem('user', JSON.stringify({ role: 'user' })); |
| |
| render( |
| <MemoryRouter> |
| <PermissionRoute requiredRoles={['admin']}> |
| <div>管理员内容</div> |
| </PermissionRoute> |
| </MemoryRouter> |
| ); |
| |
| // 应该看到重定向组件 |
| expect(screen.getByTestId('navigate-mock')).toBeInTheDocument(); |
| }); |
| |
| it('用户有所需角色时应该显示子组件', () => { |
| // 模拟管理员 |
| window.localStorage.setItem('user', JSON.stringify({ role: 'admin' })); |
| |
| render( |
| <MemoryRouter> |
| <PermissionRoute requiredRoles={['admin']}> |
| <div>管理员内容</div> |
| </PermissionRoute> |
| </MemoryRouter> |
| ); |
| |
| // 应该看到管理员内容 |
| expect(screen.getByText('管理员内容')).toBeInTheDocument(); |
| }); |
| }); |