| import { describe, it, expect, beforeEach } from 'vitest'; |
| import { render, screen } from '@testing-library/react'; |
| import { AuthProvider, useAuth } from './AuthContext'; |
| |
| // 创建一个测试组件来使用 useAuth hook |
| const TestComponent = () => { |
| const { user, hasRole } = useAuth(); |
| return ( |
| <div> |
| <div data-testid="user-info">{user ? JSON.stringify(user) : 'no user'}</div> |
| <div data-testid="is-admin">{hasRole('admin') ? 'is admin' : 'not admin'}</div> |
| </div> |
| ); |
| }; |
| |
| describe('AuthContext', () => { |
| beforeEach(() => { |
| window.localStorage.clear(); |
| }); |
| |
| it('应该提供默认值', () => { |
| render( |
| <AuthProvider> |
| <TestComponent /> |
| </AuthProvider> |
| ); |
| |
| expect(screen.getByTestId('user-info')).toHaveTextContent('no user'); |
| expect(screen.getByTestId('is-admin')).toHaveTextContent('not admin'); |
| }); |
| |
| it('应该从 localStorage 加载用户信息', () => { |
| // 模拟管理员 |
| window.localStorage.setItem('user', JSON.stringify({ |
| username: 'admin', |
| role: 'admin' |
| })); |
| |
| render( |
| <AuthProvider> |
| <TestComponent /> |
| </AuthProvider> |
| ); |
| |
| expect(screen.getByTestId('user-info')).toHaveTextContent('admin'); |
| expect(screen.getByTestId('is-admin')).toHaveTextContent('is admin'); |
| }); |
| }); |