freshyo/apps/user-ui/tests/mocks/auth-context.tsx
2026-10-18 21:51:01 +05:30

69 lines
1.8 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Deterministic AuthContext replacement.
*
* Tests that need an exact auth state (loading / signed-out / signed-in without
* the real provider's async bootstrap) mock the module:
*
* jest.mock('@/src/contexts/AuthContext', () => require('../../mocks/auth-context'))
* __setAuthState({ isAuthenticated: true, isLoading: false, user: AUTH_USER })
*/
import * as React from 'react'
export interface MockAuthState {
user: any
userDetails: any
isAuthenticated: boolean
isLoading: boolean
token: string | null
}
const initialState: MockAuthState = {
user: null,
userDetails: null,
isAuthenticated: false,
isLoading: false,
token: null,
}
let state: MockAuthState = { ...initialState }
export const login = jest.fn(async () => undefined)
export const loginWithToken = jest.fn(async () => undefined)
export const register = jest.fn(async () => undefined)
export const logout = jest.fn(async () => undefined)
export const updateUser = jest.fn()
export const updateUserDetails = jest.fn()
export function __setAuthState(next: Partial<MockAuthState>) {
state = { ...state, ...next }
}
export function __resetAuthState() {
state = { ...initialState }
login.mockClear()
loginWithToken.mockClear()
register.mockClear()
logout.mockClear()
}
export function getAuthState(): MockAuthState {
return state
}
export const AuthProvider = ({ children }: any) => React.createElement(React.Fragment, null, children)
export const useAuth = () => ({
...state,
login,
loginWithToken,
register,
logout,
updateUser,
updateUserDetails,
})
export const useAuthOptional = () => useAuth()
export const useUserDetails = () => state.userDetails
export default { AuthProvider, useAuth, useAuthOptional, useUserDetails }