185 lines
5.9 KiB
TypeScript
185 lines
5.9 KiB
TypeScript
/**
|
|
* staff-auth-context (components/context/staff-auth-context.tsx) — the REAL
|
|
* provider. tests/setup.ts mocks this module globally, so it is unmocked here.
|
|
*
|
|
* It imports the `@/utils/queryClient` singleton (cleared between tests) and
|
|
* needs expo-router (mocked) plus the trpc/React Query provider stack.
|
|
*/
|
|
|
|
jest.unmock('@/components/context/staff-auth-context')
|
|
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
|
|
|
import React from 'react'
|
|
import { DeviceEventEmitter } from 'react-native'
|
|
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
|
import { MyText, MyTouchableOpacity } from 'common-ui'
|
|
|
|
import {
|
|
StaffAuthProvider,
|
|
useStaffAuth,
|
|
} from '@/components/context/staff-auth-context'
|
|
import { getJWT, saveJWT } from '@/hooks/useJWT'
|
|
import queryClient from '@/utils/queryClient'
|
|
import { FORCE_LOGOUT_EVENT } from 'common-ui/src/lib/const-strs'
|
|
import { resetStorage, setupApiMocks } from '../mocks/api'
|
|
import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures'
|
|
import { resetRouterMock, routerMock } from '../mocks/router'
|
|
import { renderWithProviders } from '../helpers/render'
|
|
|
|
type Auth = ReturnType<typeof useStaffAuth>
|
|
|
|
const authSpy = jest.fn<void, [Auth]>()
|
|
|
|
function Consumer() {
|
|
const auth = useStaffAuth()
|
|
authSpy(auth)
|
|
|
|
return (
|
|
<>
|
|
<MyTouchableOpacity testID="login" onPress={() => auth.login('shafi', 'secret')}>
|
|
<MyText>login</MyText>
|
|
</MyTouchableOpacity>
|
|
<MyTouchableOpacity testID="logout" onPress={() => auth.logout()}>
|
|
<MyText>logout</MyText>
|
|
</MyTouchableOpacity>
|
|
</>
|
|
)
|
|
}
|
|
|
|
const lastAuth = (): Auth => authSpy.mock.calls[authSpy.mock.calls.length - 1][0]
|
|
|
|
const renderProvider = () =>
|
|
renderWithProviders(
|
|
<StaffAuthProvider>
|
|
<Consumer />
|
|
</StaffAuthProvider>
|
|
)
|
|
|
|
const trpcErrorResponse = (message: string) => [
|
|
{ error: { message, code: -32600, data: { code: 'UNAUTHORIZED', httpStatus: 401 } } },
|
|
]
|
|
|
|
describe('staff-auth-context (real provider)', () => {
|
|
beforeEach(async () => {
|
|
authSpy.mockClear()
|
|
queryClient.clear()
|
|
resetRouterMock()
|
|
await resetStorage()
|
|
setupApiMocks({
|
|
procedures: {
|
|
'admin.staffUser.login': { token: 'jwt-abc', staff: { id: 1, name: 'shafi' } },
|
|
},
|
|
})
|
|
})
|
|
|
|
it('redirects to /login when there is no token', async () => {
|
|
renderProvider()
|
|
|
|
await waitFor(() => expect(routerMock.replace).toHaveBeenCalledWith('/login'))
|
|
await waitFor(() => expect(lastAuth().isLoading).toBe(false))
|
|
expect(lastAuth().isLoggedIn).toBe(false)
|
|
expect(lastAuth().staff).toBeNull()
|
|
})
|
|
|
|
it('marks the session logged in when a token exists', async () => {
|
|
await saveJWT('existing-token')
|
|
|
|
renderProvider()
|
|
|
|
await waitFor(() => expect(lastAuth().isLoggedIn).toBe(true))
|
|
expect(lastAuth().isLoading).toBe(false)
|
|
expect(routerMock.replace).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('login saves the JWT, sets staff and routes to the dashboard', async () => {
|
|
const { fetchMock } = setupApiMocks({
|
|
procedures: {
|
|
'admin.staffUser.login': { token: 'jwt-abc', staff: { id: 7, name: 'shafi' } },
|
|
},
|
|
})
|
|
|
|
renderProvider()
|
|
await waitFor(() => expect(lastAuth().isLoading).toBe(false))
|
|
|
|
fireEvent.press(screen.getByTestId('login'))
|
|
|
|
await waitFor(() =>
|
|
expect(routerMock.replace).toHaveBeenCalledWith('/(drawer)/dashboard')
|
|
)
|
|
await waitFor(async () => expect(await getJWT()).toBe('jwt-abc'))
|
|
|
|
expect(lastAuth().staff).toEqual({ id: 7, name: 'shafi' })
|
|
expect(lastAuth().isLoggedIn).toBe(true)
|
|
expect(lastAuth().loginError).toBeNull()
|
|
|
|
expectProcedureCalled(fetchMock, 'admin.staffUser.login', { times: 1 })
|
|
expect(lastProcedureInput(fetchMock, 'admin.staffUser.login')).toEqual({
|
|
name: 'shafi',
|
|
password: 'secret',
|
|
})
|
|
})
|
|
|
|
it('login sets loginError when the backend rejects', async () => {
|
|
setupApiMocks()
|
|
;(global as unknown as { fetch: unknown }).fetch = jest.fn(async () => ({
|
|
ok: true,
|
|
status: 200,
|
|
statusText: 'OK',
|
|
headers: new Map(),
|
|
url: '',
|
|
json: async () => trpcErrorResponse('Invalid credentials'),
|
|
text: async () => JSON.stringify(trpcErrorResponse('Invalid credentials')),
|
|
}))
|
|
|
|
renderProvider()
|
|
await waitFor(() => expect(lastAuth().isLoading).toBe(false))
|
|
|
|
fireEvent.press(screen.getByTestId('login'))
|
|
|
|
await waitFor(() => expect(lastAuth().loginError).toBe('Invalid credentials'))
|
|
expect(lastAuth().isLoggedIn).toBe(false)
|
|
expect(routerMock.replace).not.toHaveBeenCalledWith('/(drawer)/dashboard')
|
|
})
|
|
|
|
it('logout deletes the JWT, clears the query cache and routes to /login', async () => {
|
|
await saveJWT('existing-token')
|
|
const clearSpy = jest.spyOn(queryClient, 'clear')
|
|
|
|
renderProvider()
|
|
await waitFor(() => expect(lastAuth().isLoggedIn).toBe(true))
|
|
|
|
fireEvent.press(screen.getByTestId('logout'))
|
|
|
|
await waitFor(() => expect(routerMock.replace).toHaveBeenCalledWith('/login'))
|
|
await waitFor(async () => expect(await getJWT()).toBeNull())
|
|
|
|
expect(clearSpy).toHaveBeenCalled()
|
|
expect(lastAuth().isLoggedIn).toBe(false)
|
|
expect(lastAuth().staff).toBeNull()
|
|
})
|
|
|
|
it('FORCE_LOGOUT_EVENT logs the staff member out', async () => {
|
|
await saveJWT('existing-token')
|
|
|
|
renderProvider()
|
|
await waitFor(() => expect(lastAuth().isLoggedIn).toBe(true))
|
|
|
|
await act(async () => {
|
|
DeviceEventEmitter.emit(FORCE_LOGOUT_EVENT)
|
|
})
|
|
|
|
await waitFor(() => expect(routerMock.replace).toHaveBeenCalledWith('/login'))
|
|
await waitFor(async () => expect(await getJWT()).toBeNull())
|
|
expect(lastAuth().isLoggedIn).toBe(false)
|
|
})
|
|
|
|
it('useStaffAuth throws when used outside the provider', () => {
|
|
const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {})
|
|
|
|
expect(() => renderWithProviders(<Consumer />)).toThrow(
|
|
'useStaffAuth must be used within a StaffAuthProvider'
|
|
)
|
|
|
|
consoleError.mockRestore()
|
|
})
|
|
})
|