auth-store.test.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { beforeEach, describe, expect, it, vi } from 'vitest'
  2. function clearAllCookies() {
  3. for (const part of document.cookie.split(';')) {
  4. const name = part.split('=')[0]?.trim()
  5. if (!name) continue
  6. document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`
  7. }
  8. }
  9. async function importAuthStore() {
  10. const { useAuthStore } = await import('./auth-store')
  11. return useAuthStore
  12. }
  13. const sampleUser = {
  14. accountNo: 'ACC-1',
  15. email: 'user@example.com',
  16. role: ['user'],
  17. exp: 1_700_000_000,
  18. }
  19. describe('useAuthStore', () => {
  20. beforeEach(() => {
  21. clearAllCookies()
  22. vi.resetModules()
  23. })
  24. it('starts with an empty access token when nothing is persisted', async () => {
  25. const useAuthStore = await importAuthStore()
  26. expect(useAuthStore.getState().auth.accessToken).toBe('')
  27. expect(useAuthStore.getState().auth.user).toBeNull()
  28. })
  29. it('persists access token so a new store instance reads it back', async () => {
  30. const useAuthStore = await importAuthStore()
  31. useAuthStore.getState().auth.setAccessToken('session-token')
  32. vi.resetModules()
  33. const useAuthStoreAfterReload = await importAuthStore()
  34. expect(useAuthStoreAfterReload.getState().auth.accessToken).toBe(
  35. 'session-token'
  36. )
  37. })
  38. it('clears persisted access token when resetAccessToken is used', async () => {
  39. const useAuthStore = await importAuthStore()
  40. useAuthStore.getState().auth.setAccessToken('to-clear')
  41. useAuthStore.getState().auth.resetAccessToken()
  42. vi.resetModules()
  43. const useAuthStoreAfterReload = await importAuthStore()
  44. expect(useAuthStoreAfterReload.getState().auth.accessToken).toBe('')
  45. })
  46. it('updates the signed-in user via setUser', async () => {
  47. const useAuthStore = await importAuthStore()
  48. useAuthStore.getState().auth.setUser({ ...sampleUser })
  49. expect(useAuthStore.getState().auth.user).toEqual(sampleUser)
  50. })
  51. it('reset clears user and access token and drops persistence', async () => {
  52. const useAuthStore = await importAuthStore()
  53. useAuthStore.getState().auth.setAccessToken('will-be-cleared')
  54. useAuthStore.getState().auth.setUser({ ...sampleUser })
  55. useAuthStore.getState().auth.reset()
  56. expect(useAuthStore.getState().auth.user).toBeNull()
  57. expect(useAuthStore.getState().auth.accessToken).toBe('')
  58. vi.resetModules()
  59. const useAuthStoreAfterReload = await importAuthStore()
  60. expect(useAuthStoreAfterReload.getState().auth.user).toBeNull()
  61. expect(useAuthStoreAfterReload.getState().auth.accessToken).toBe('')
  62. })
  63. })