freshyo/apps/user-ui/tests/lib/auth.test.tsx
2026-10-20 11:19:25 +05:30

287 lines
9.8 KiB
TypeScript

/* 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 } from 'react-native'
import { act, waitFor } from '@testing-library/react-native'
import { StorageService } from 'common-ui'
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 (
<Text testID="auth-state">
{`${ctx.isAuthenticated ? 'in' : 'out'}:${ctx.isLoading ? 'loading' : 'ready'}`}
</Text>
)
}
/** Run a context async action inside act, capturing a thrown error. */
async function invoke(action: (current: any) => Promise<void> | 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(<AuthProbe />, { 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: is authenticated but still loading while getSelfData is pending', async () => {
setProcedure('user.user.getSelfData', { mode: 'pending' })
renderWithProviders(<AuthProbe />, { auth: 'in' })
await waitFor(() => expect(ctx.isAuthenticated).toBe(true))
expect(ctx.isLoading).toBe(true)
expect(ctx.token).toBe(TEST_JWT)
})
it('AUTH-03: populates user and userDetails from getSelfData', async () => {
renderWithProviders(<AuthProbe />, { 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: signs out when getSelfData fails but keeps the stored token', async () => {
setProcedure('user.user.getSelfData', {
mode: 'error',
error: new Error('unauthorized'),
})
renderWithProviders(<AuthProbe />, { auth: 'in' })
// `isAuthenticated` starts false, so wait for the bootstrap + self read to
// settle (the signed-in state is too short-lived for a poll to catch), then
// assert the failure signed the user out.
await waitFor(() => expect(ctx.isLoading).toBe(false))
expect(ctx.isAuthenticated).toBe(false)
// Current behaviour: deleteAuthToken() is commented out.
expect(__snapshot().authToken).toBe(TEST_JWT)
})
it('AUTH-05: loginWithToken stores token/userId and runs the redirect handler', async () => {
renderWithProviders(<AuthProbe />, { 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(<AuthProbe />, { 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(<AuthProbe />, { 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(<AuthProbe />, { 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(<AuthProbe />, { 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(<AuthProbe />, { 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(<AuthProbe />, { 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(<AuthProbe />, { 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(<AuthProbe />, { 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(<AuthProbe />, { 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(<AuthProbe />, { 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(<AuthProbe />, { 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(<AuthProbe />, { 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(<AuthProbe />, { auth: 'in' })
await flush()
await invoke((auth) => auth.loginWithToken('t', AUTH_USER as any))
await waitFor(() => expect(router.replace).toHaveBeenCalledWith('/'))
})
})