authSlice.test.ts
1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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');
});
});