浏览代码

test: add tests for auth store

satnaing 2 月之前
父节点
当前提交
755326e13f
共有 1 个文件被更改,包括 83 次插入0 次删除
  1. 83 0
      src/stores/auth-store.test.ts

+ 83 - 0
src/stores/auth-store.test.ts

@@ -0,0 +1,83 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+function clearAllCookies() {
+  for (const part of document.cookie.split(';')) {
+    const name = part.split('=')[0]?.trim()
+    if (!name) continue
+    document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`
+  }
+}
+
+async function importAuthStore() {
+  const { useAuthStore } = await import('./auth-store')
+  return useAuthStore
+}
+
+const sampleUser = {
+  accountNo: 'ACC-1',
+  email: 'user@example.com',
+  role: ['user'],
+  exp: 1_700_000_000,
+}
+
+describe('useAuthStore', () => {
+  beforeEach(() => {
+    clearAllCookies()
+    vi.resetModules()
+  })
+
+  it('starts with an empty access token when nothing is persisted', async () => {
+    const useAuthStore = await importAuthStore()
+
+    expect(useAuthStore.getState().auth.accessToken).toBe('')
+    expect(useAuthStore.getState().auth.user).toBeNull()
+  })
+
+  it('persists access token so a new store instance reads it back', async () => {
+    const useAuthStore = await importAuthStore()
+    useAuthStore.getState().auth.setAccessToken('session-token')
+
+    vi.resetModules()
+    const useAuthStoreAfterReload = await importAuthStore()
+
+    expect(useAuthStoreAfterReload.getState().auth.accessToken).toBe(
+      'session-token'
+    )
+  })
+
+  it('clears persisted access token when resetAccessToken is used', async () => {
+    const useAuthStore = await importAuthStore()
+    useAuthStore.getState().auth.setAccessToken('to-clear')
+    useAuthStore.getState().auth.resetAccessToken()
+
+    vi.resetModules()
+    const useAuthStoreAfterReload = await importAuthStore()
+
+    expect(useAuthStoreAfterReload.getState().auth.accessToken).toBe('')
+  })
+
+  it('updates the signed-in user via setUser', async () => {
+    const useAuthStore = await importAuthStore()
+
+    useAuthStore.getState().auth.setUser({ ...sampleUser })
+
+    expect(useAuthStore.getState().auth.user).toEqual(sampleUser)
+  })
+
+  it('reset clears user and access token and drops persistence', async () => {
+    const useAuthStore = await importAuthStore()
+    useAuthStore.getState().auth.setAccessToken('will-be-cleared')
+    useAuthStore.getState().auth.setUser({ ...sampleUser })
+
+    useAuthStore.getState().auth.reset()
+
+    expect(useAuthStore.getState().auth.user).toBeNull()
+    expect(useAuthStore.getState().auth.accessToken).toBe('')
+
+    vi.resetModules()
+    const useAuthStoreAfterReload = await importAuthStore()
+
+    expect(useAuthStoreAfterReload.getState().auth.user).toBeNull()
+    expect(useAuthStoreAfterReload.getState().auth.accessToken).toBe('')
+  })
+})