Files
oci-portal-dash/src/stores/auth.test.ts
T
2026-07-22 16:51:45 +08:00

50 lines
1.4 KiB
TypeScript

import { beforeEach, describe, expect, it } from 'vitest'
import { createPinia, setActivePinia } from 'pinia'
import { useAuthStore } from './auth'
beforeEach(() => {
localStorage.clear()
setActivePinia(createPinia())
})
describe('isAuthed 实时过期判定', () => {
const cases = [
{ name: '无 token 未登录', token: '', expiresAt: '', want: false },
{ name: '有 token 无过期时间视为已登录', token: 't', expiresAt: '', want: true },
{
name: '未过期',
token: 't',
expiresAt: new Date(Date.now() + 60_000).toISOString(),
want: true,
},
{
name: '已过期(computed 缓存会误判的场景)',
token: 't',
expiresAt: new Date(Date.now() - 1_000).toISOString(),
want: false,
},
]
for (const c of cases) {
it(c.name, () => {
const auth = useAuthStore()
if (c.token) auth.setSession(c.token, c.expiresAt)
expect(auth.isAuthed()).toBe(c.want)
})
}
})
it('logout 清空会话与本地存储', () => {
const auth = useAuthStore()
auth.setSession('t', new Date(Date.now() + 60_000).toISOString())
auth.logout()
expect(auth.token).toBe('')
expect(auth.isAuthed()).toBe(false)
expect(localStorage.getItem('oci-portal.token')).toBeNull()
})
it('setSession 落地本地存储,新 store 实例可恢复', () => {
useAuthStore().setSession('t2', '')
setActivePinia(createPinia())
expect(useAuthStore().token).toBe('t2')
})