/** * src/trpc-client.ts — a 401 UNAUTHORIZED response must emit the force-logout * event so the app can clear the session. * * httpBatchLink flushes on a timer, so waitFor drives the request to completion. */ import { DeviceEventEmitter } from 'react-native' import { waitFor } from '@testing-library/react-native' import { FORCE_LOGOUT_EVENT } from 'common-ui/src/lib/const-strs' import { trpcClient } from '@/src/trpc-client' const responseWith = (status: number, message: string) => { const body = [{ error: { message } }] return { ok: status < 400, status, statusText: 'status', headers: new Map(), url: '', json: async () => body, text: async () => JSON.stringify(body), clone: () => ({ json: async () => body }), } } /** Fire a tRPC call and wait for it to settle, advancing the batch timer. */ const callAndSettle = async (status: number, message: string) => { ;(global as unknown as { fetch: unknown }).fetch = jest.fn(async () => responseWith(status, message) ) let settled = false const promise = trpcClient.common.healthCheck .query() .catch(() => undefined) .then(() => { settled = true }) await waitFor(() => expect(settled).toBe(true)) await promise } describe('trpc-client', () => { it('emits the force-logout event on a 401 UNAUTHORIZED response', async () => { const emit = jest.spyOn(DeviceEventEmitter, 'emit') await callAndSettle(401, 'UNAUTHORIZED') expect(emit).toHaveBeenCalledWith(FORCE_LOGOUT_EVENT) }) it('does not emit the force-logout event on a 500 response', async () => { const emit = jest.spyOn(DeviceEventEmitter, 'emit') await callAndSettle(500, 'Internal Server Error') expect(emit).not.toHaveBeenCalledWith(FORCE_LOGOUT_EVENT) }) })