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, Routes, Route } from 'react-router-dom'; |
| 4 | import ProtectedRoute from './ProtectedRoute'; |
| 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('ProtectedRoute 组件', () => { |
| 16 | beforeEach(() => { |
| 17 | window.localStorage.clear(); |
| 18 | }); |
| 19 | |
| 20 | it('未登录时应该重定向到登录页', () => { |
| 21 | render( |
| 22 | <MemoryRouter> |
| 23 | <ProtectedRoute> |
| 24 | <div>受保护的内容</div> |
| 25 | </ProtectedRoute> |
| 26 | </MemoryRouter> |
| 27 | ); |
| 28 | |
| 29 | // 应该看到重定向组件 |
| 30 | expect(screen.getByTestId('navigate-mock')).toBeInTheDocument(); |
| 31 | }); |
| 32 | |
| 33 | it('已登录时应该显示子组件', () => { |
| 34 | // 模拟已登录状态 |
| 35 | window.localStorage.setItem('token', 'fake-token'); |
| 36 | |
| 37 | render( |
| 38 | <MemoryRouter> |
| 39 | <ProtectedRoute> |
| 40 | <div>受保护的内容</div> |
| 41 | </ProtectedRoute> |
| 42 | </MemoryRouter> |
| 43 | ); |
| 44 | |
| 45 | // 应该看到受保护的内容 |
| 46 | expect(screen.getByText('受保护的内容')).toBeInTheDocument(); |
| 47 | }); |
| 48 | }); |