import { describe, it, expect, beforeEach, vi } from 'vitest'; import authReducer, { setCredentials, clearCredentials, type AuthState, } from '../../src/store/slices/authSlice'; import { TOKEN_STORAGE_KEY } from '../../src/api/request'; import type { AuthUser } from '../../src/api/types'; const user: AuthUser = { id: 1, sUserName: 'admin', sUserType: '超级管理员', sLanguage: '中文' }; describe('authSlice', () => { beforeEach(() => { localStorage.clear(); }); it('setCredentials stores token and user and persists token', () => { const start: AuthState = { token: null, user: null }; const next = authReducer(start, setCredentials({ token: 't', user })); expect(next.token).toBe('t'); expect(next.user).toEqual(user); expect(localStorage.getItem(TOKEN_STORAGE_KEY)).toBe('t'); }); it('clearCredentials clears state and removes persisted token', () => { localStorage.setItem(TOKEN_STORAGE_KEY, 't'); const start: AuthState = { token: 't', user }; const next = authReducer(start, clearCredentials()); expect(next.token).toBeNull(); expect(next.user).toBeNull(); expect(localStorage.getItem(TOKEN_STORAGE_KEY)).toBeNull(); }); it('initialState reads persisted token', async () => { localStorage.setItem(TOKEN_STORAGE_KEY, 'persisted-tk'); // 重置模块缓存,使 initialState 在带 token 的 localStorage 下重新求值 vi.resetModules(); const mod = await import('../../src/store/slices/authSlice'); const initial = mod.default(undefined, { type: '@@INIT' }); expect(initial.token).toBe('persisted-tk'); }); });