ybt | 02e716d | 2025-04-15 17:19:32 +0800 | [diff] [blame^] | 1 | import { describe, it, expect, beforeEach } from 'vitest'; |
| 2 | import { render, screen } from '@testing-library/react'; |
| 3 | import { AuthProvider, useAuth } from './AuthContext'; |
| 4 | |
| 5 | // 创建一个测试组件来使用 useAuth hook |
| 6 | const TestComponent = () => { |
| 7 | const { user, hasRole } = useAuth(); |
| 8 | return ( |
| 9 | <div> |
| 10 | <div data-testid="user-info">{user ? JSON.stringify(user) : 'no user'}</div> |
| 11 | <div data-testid="is-admin">{hasRole('admin') ? 'is admin' : 'not admin'}</div> |
| 12 | </div> |
| 13 | ); |
| 14 | }; |
| 15 | |
| 16 | describe('AuthContext', () => { |
| 17 | beforeEach(() => { |
| 18 | window.localStorage.clear(); |
| 19 | }); |
| 20 | |
| 21 | it('应该提供默认值', () => { |
| 22 | render( |
| 23 | <AuthProvider> |
| 24 | <TestComponent /> |
| 25 | </AuthProvider> |
| 26 | ); |
| 27 | |
| 28 | expect(screen.getByTestId('user-info')).toHaveTextContent('no user'); |
| 29 | expect(screen.getByTestId('is-admin')).toHaveTextContent('not admin'); |
| 30 | }); |
| 31 | |
| 32 | it('应该从 localStorage 加载用户信息', () => { |
| 33 | // 模拟管理员 |
| 34 | window.localStorage.setItem('user', JSON.stringify({ |
| 35 | username: 'admin', |
| 36 | role: 'admin' |
| 37 | })); |
| 38 | |
| 39 | render( |
| 40 | <AuthProvider> |
| 41 | <TestComponent /> |
| 42 | </AuthProvider> |
| 43 | ); |
| 44 | |
| 45 | expect(screen.getByTestId('user-info')).toHaveTextContent('admin'); |
| 46 | expect(screen.getByTestId('is-admin')).toHaveTextContent('is admin'); |
| 47 | }); |
| 48 | }); |