/* eslint-disable @typescript-eslint/no-explicit-any */ /** * AUTH-01..AUTH-17 from JEST-TEST-CASES.md section 25. * * These exercise the *real* `AuthProvider` from `src/contexts/AuthContext.tsx` * (no `auth-context` mock here): the shared trpc procedure registry stands in * for the network, `expo-secure-store` is the in-memory mock, and `expo-router` * is recorded rather than navigated. */ import * as React from 'react' import { Text, DeviceEventEmitter } from 'react-native' import { act, waitFor } from '@testing-library/react-native' import { StorageService } from 'common-ui' import { FORCE_LOGOUT_EVENT } from 'common-ui/src/lib/const-strs' import { useAuth } from '@/src/contexts/AuthContext' import { getAuthToken, getUserId } from '@/hooks/useJWT' import constants from '@/src/constants' import { renderWithProviders, flush, createTestQueryClient, } from '../helpers/test-utils' import { resetAllMocks } from '../helpers/reset' import { router } from '../mocks/expo-router-mock' import { __set, __snapshot } from '../mocks/secure-store-mock' import { setProcedure, lastProcedureInput } from '../mocks/trpc-client' import { AUTH_USER, AUTH_USER_FULL, TEST_JWT } from '../fixtures' let ctx: any function AuthProbe() { ctx = useAuth() return ( {`${ctx.isAuthenticated ? 'in' : 'out'}:${ctx.isLoading ? 'loading' : 'ready'}`} ) } /** Run a context async action inside act, capturing a thrown error. */ async function invoke(action: (current: any) => Promise | void) { let error: unknown = null await act(async () => { try { await action(ctx) } catch (err) { error = err } }) await flush(2) return error } describe('AuthContext', () => { beforeEach(() => resetAllMocks()) it('AUTH-01: starts signed out and not loading when there is no token/userId', async () => { renderWithProviders(, { auth: 'out' }) await waitFor(() => expect(ctx.isLoading).toBe(false)) expect(ctx.isAuthenticated).toBe(false) expect(ctx.token).toBeNull() expect(ctx.user).toBeNull() }) it('AUTH-02: trusts the stored token and does not block on getSelfData', async () => { setProcedure('user.user.getSelfData', { mode: 'pending' }) renderWithProviders(, { auth: 'in' }) await waitFor(() => expect(ctx.isAuthenticated).toBe(true)) expect(ctx.isLoading).toBe(false) expect(ctx.token).toBe(TEST_JWT) }) it('AUTH-03: populates user and userDetails from getSelfData', async () => { renderWithProviders(, { auth: 'in' }) await waitFor(() => expect(ctx.isLoading).toBe(false)) expect(ctx.user.name).toBe('Test User') expect(ctx.user.email).toBe('test@example.com') expect(ctx.userDetails).toEqual(AUTH_USER_FULL) }) it('AUTH-04: logs out when the backend rejects the stored token', async () => { setProcedure('user.user.getSelfData', { mode: 'error', error: new Error('unauthorized'), errorCode: 'UNAUTHORIZED', }) renderWithProviders(, { auth: 'in' }) // The token is present until the rejection lands, so this waits for the // effect instead of racing the initial signed-out render. await waitFor(() => expect(__snapshot().authToken).toBeUndefined()) expect(ctx.isAuthenticated).toBe(false) expect(ctx.isLoading).toBe(false) expect(ctx.user).toBeNull() }) it('AUTH-05: loginWithToken stores token/userId and runs the redirect handler', async () => { renderWithProviders(, { auth: 'in' }) await flush() const error = await invoke((auth) => auth.loginWithToken('custom-token', { ...AUTH_USER, id: 9 }) ) expect(error).toBeNull() expect(await getAuthToken()).toBe('custom-token') expect(await getUserId()).toBe('9') expect(ctx.isAuthenticated).toBe(true) // No stored redirect state -> fall back to the previous screen. expect(router.back).toHaveBeenCalled() }) it('AUTH-06: surfaces a storage failure from loginWithToken and stops loading', async () => { renderWithProviders(, { auth: 'in' }) await flush() const spy = jest .spyOn(StorageService, 'setItem') .mockRejectedValueOnce(new Error('disk full')) const error = await invoke((auth) => auth.loginWithToken('t', AUTH_USER as any)) spy.mockRestore() expect(error).toBeInstanceOf(Error) expect(ctx.isLoading).toBe(false) }) it('AUTH-07: login calls the login mutation, stores the token and marks the user in', async () => { const credentials = { mobile: '9876543210' } renderWithProviders(, { auth: 'in' }) await flush() const error = await invoke((auth) => auth.login(credentials as any)) expect(error).toBeNull() expect(lastProcedureInput('user.auth.login')).toEqual(credentials) expect(await getAuthToken()).toBe('test-token') expect(await getUserId()).toBe('5') expect(ctx.isAuthenticated).toBe(true) }) it('AUTH-08: login failure stops loading and rethrows', async () => { setProcedure('user.auth.login', { mode: 'error', error: new Error('bad creds') }) renderWithProviders(, { auth: 'in' }) await flush() const error = await invoke((auth) => auth.login({ mobile: '1' } as any)) expect(error).toBeInstanceOf(Error) expect(ctx.isLoading).toBe(false) }) it('AUTH-09: register calls the register mutation and stores the token', async () => { const data = { mobile: '9876543210', otp: '1234', name: 'Test User' } renderWithProviders(, { auth: 'in' }) await flush() const error = await invoke((auth) => auth.register(data as any)) expect(error).toBeNull() expect(lastProcedureInput('user.auth.register')).toEqual(data) expect(await getAuthToken()).toBe('test-token') expect(await getUserId()).toBe('5') expect(ctx.isAuthenticated).toBe(true) }) it('AUTH-10: register failure stops loading and rethrows', async () => { setProcedure('user.auth.register', { mode: 'error', error: new Error('taken') }) renderWithProviders(, { auth: 'in' }) await flush() const error = await invoke((auth) => auth.register({ mobile: '1' } as any)) expect(error).toBeInstanceOf(Error) expect(ctx.isLoading).toBe(false) }) it('AUTH-11: logout clears the token, the query client and the auth state', async () => { const queryClient = createTestQueryClient() renderWithProviders(, { auth: 'in', queryClient }) await flush() const clearSpy = jest.spyOn(queryClient, 'clear') await invoke((auth) => auth.logout()) expect(clearSpy).toHaveBeenCalled() expect(__snapshot().authToken).toBeUndefined() expect(ctx.isAuthenticated).toBe(false) expect(ctx.user).toBeNull() }) it('AUTH-12: logout still clears state and cache when deleting the token fails', async () => { const queryClient = createTestQueryClient() renderWithProviders(, { auth: 'in', queryClient }) await flush() const clearSpy = jest.spyOn(queryClient, 'clear') const spy = jest .spyOn(StorageService, 'removeItem') .mockRejectedValueOnce(new Error('offline')) await invoke((auth) => auth.logout()) spy.mockRestore() expect(clearSpy).toHaveBeenCalled() expect(ctx.isAuthenticated).toBe(false) expect(ctx.user).toBeNull() }) it('AUTH-13: updateUser/updateUserDetails merge and are null safe', async () => { const first = renderWithProviders(, { auth: 'in' }) await waitFor(() => expect(ctx.userDetails).not.toBeNull()) act(() => ctx.updateUser({ name: 'Renamed' })) expect(ctx.user.name).toBe('Renamed') expect(ctx.user.email).toBe('test@example.com') act(() => ctx.updateUserDetails({ bio: 'hello' } as any)) expect(ctx.userDetails.bio).toBe('hello') first.unmount() renderWithProviders(, { auth: 'out' }) await flush() expect(ctx.user).toBeNull() act(() => { ctx.updateUser({ name: 'x' }) ctx.updateUserDetails({ bio: 'y' } as any) }) expect(ctx.user).toBeNull() expect(ctx.userDetails).toBeNull() }) it('AUTH-14: valid redirect state removes the key and replaces with target + params', async () => { __set( constants.AUTH_REDIRECT_KEY, JSON.stringify({ targetUrl: '/orders', queryParams: { id: 1, drop: null }, timestamp: Date.now(), }) ) renderWithProviders(, { auth: 'in' }) await flush() await invoke((auth) => auth.loginWithToken('t', AUTH_USER as any)) await waitFor(() => expect(router.replace).toHaveBeenCalledWith('/orders?id=1')) expect(__snapshot()[constants.AUTH_REDIRECT_KEY]).toBeUndefined() }) it('AUTH-15: redirect state older than 24h replaces with home', async () => { __set( constants.AUTH_REDIRECT_KEY, JSON.stringify({ targetUrl: '/orders', queryParams: {}, timestamp: Date.now() - 25 * 60 * 60 * 1000, }) ) renderWithProviders(, { auth: 'in' }) await flush() await invoke((auth) => auth.loginWithToken('t', AUTH_USER as any)) await waitFor(() => expect(router.replace).toHaveBeenCalledWith('/')) }) it('AUTH-16: no redirect state falls back to router.back()', async () => { renderWithProviders(, { auth: 'in' }) await flush() await invoke((auth) => auth.loginWithToken('t', AUTH_USER as any)) await waitFor(() => expect(router.back).toHaveBeenCalled()) expect(router.replace).not.toHaveBeenCalled() }) it('AUTH-17: corrupt redirect JSON replaces with home', async () => { __set(constants.AUTH_REDIRECT_KEY, 'not-json{') renderWithProviders(, { auth: 'in' }) await flush() await invoke((auth) => auth.loginWithToken('t', AUTH_USER as any)) await waitFor(() => expect(router.replace).toHaveBeenCalledWith('/')) }) it('AUTH-18: a non-credential getSelfData failure keeps the trusted session', async () => { // Offline / timeout / 5xx must not wipe the credentials. setProcedure('user.user.getSelfData', { mode: 'error', error: new Error('network down'), errorCode: 'INTERNAL_SERVER_ERROR', }) renderWithProviders(, { auth: 'in' }) await waitFor(() => expect(ctx.isLoading).toBe(false)) expect(ctx.isAuthenticated).toBe(true) expect(ctx.user).not.toBeNull() expect(__snapshot().authToken).toBe(TEST_JWT) }) it('AUTH-19: a force-logout event (401 from any endpoint) clears the session', async () => { renderWithProviders(, { auth: 'in' }) await waitFor(() => expect(ctx.isAuthenticated).toBe(true)) act(() => { DeviceEventEmitter.emit(FORCE_LOGOUT_EVENT) }) await waitFor(() => expect(__snapshot().authToken).toBeUndefined()) expect(ctx.isAuthenticated).toBe(false) expect(ctx.token).toBeNull() }) })