Files
nuxt4/tests/auth.store.spec.ts
2026-05-03 07:26:12 +00:00

68 lines
1.7 KiB
TypeScript

import { beforeEach, describe, expect, it } from 'vitest'
import { createPinia, setActivePinia } from 'pinia'
import { useAuthStore, type AuthUser } from '../app/stores/auth'
describe('useAuthStore', () => {
const baseUser: AuthUser = {
id: 'user-1',
email: 'john@example.com',
firstName: 'John',
lastName: 'Doe',
roles: ['USER', 'ADMIN']
}
beforeEach(() => {
setActivePinia(createPinia())
})
it('initializes authenticated session state from a user', () => {
const store = useAuthStore()
store.initialize(baseUser)
expect(store.isInitialized).toBe(true)
expect(store.isAuthenticated).toBe(true)
expect(store.user).toEqual(baseUser)
expect(store.roles).toEqual(['USER', 'ADMIN'])
expect(store.displayName).toBe('John Doe')
})
it('falls back to email or id when full name is not available', () => {
const store = useAuthStore()
store.setUser({
id: 'user-2',
email: 'fallback@example.com',
roles: ['USER']
})
expect(store.displayName).toBe('fallback@example.com')
store.setUser({
id: 'user-3',
roles: ['USER']
})
expect(store.displayName).toBe('user-3')
})
it('checks roles and clears session safely', () => {
const store = useAuthStore()
store.initialize(baseUser)
expect(store.hasRole('ADMIN')).toBe(true)
expect(store.hasRole('GUEST')).toBe(false)
expect(store.hasAnyRole(['GUEST', 'ADMIN'])).toBe(true)
expect(store.hasAnyRole(['GUEST'])).toBe(false)
store.clearSession()
expect(store.isInitialized).toBe(true)
expect(store.isAuthenticated).toBe(false)
expect(store.user).toBeNull()
expect(store.roles).toEqual([])
expect(store.displayName).toBe('')
})
})