Files
gh-christianlouis-inboxconv…/frontend/src/store/authStore.ts
T
google-labs-jules[bot] 4515042acf 🧪 [testing improvement description] Implement unit tests for useAuthStore and refine store logic.
🎯 **What:** This PR adds comprehensive unit tests for the `useAuthStore` Zustand store in the frontend. It addresses a gap where no unit tests were present for authentication state management.
📊 **Coverage:** The new tests cover:
- Initial state verification.
- User state updates via `setUser`.
- Token management via `setToken`.
- Loading state toggles with `setLoading`.
- Complete logout flow, including `localStorage` cleanup.
 **Result:** Increased reliability of the authentication logic by ensuring state changes are deterministic and correctly persist/clear tokens as needed. The store implementation was also refined to properly include and handle the `token` property.

Co-authored-by: christianlouis <361235+christianlouis@users.noreply.github.com>
2026-03-23 14:36:44 +00:00

40 lines
1.0 KiB
TypeScript

import { create } from 'zustand';
import { User } from '@/lib/api';
interface AuthState {
user: User | null;
token: string | null;
isAuthenticated: boolean;
isLoading: boolean;
setUser: (user: User | null) => void;
setToken: (token: string) => void;
setLoading: (loading: boolean) => void;
logout: () => void;
}
export const useAuthStore = create<AuthState>((set) => ({
user: null,
token: typeof window !== 'undefined' ? localStorage.getItem('access_token') : null,
isAuthenticated: typeof window !== 'undefined' ? !!localStorage.getItem('access_token') : false,
isLoading: true,
setUser: (user) => set({
user,
isAuthenticated: !!user,
isLoading: false,
}),
setToken: (token: string) => {
localStorage.setItem('access_token', token);
set({ token, isAuthenticated: true });
},
setLoading: (loading) => set({ isLoading: loading }),
logout: () => {
localStorage.removeItem('access_token');
localStorage.removeItem('user');
set({ user: null, token: null, isAuthenticated: false });
},
}));