// /* eslint-disable @typescript-eslint/no-explicit-any */ // /* eslint-disable @typescript-eslint/no-require-imports */ // /** // * Section 25 "App helpers" — push notifications. // * // * Rows: NOTIF-01..07 (`registerForPushNotificationsAsync`), // * NOTIFC-01..05 (`NotificationProvider` + `NotifChecker`) and // * NOTIFR-01..07 (`NotifRegionSync`). // * // * Native swap-ins come from the shared mocks: `expo-notifications` is the // * configurable `tests/mocks/expo-notifications-mock`, `expo-device` defaults to a // * physical device and `expo-constants` carries a project id. // * // * `NotifRegionSync` reads the region through `useRegion` (covered by its own // * suite, `REGION-01..15`) so here it is replaced by a settable stub — otherwise // * every case would drag in the location fix + region resolve machinery. // */ // import * as React from 'react' // import { Linking, Modal, Platform } from 'react-native' // import { waitFor, fireEvent } from '@testing-library/react-native' // import { NOTIF_PERMISSION_DENIED } from 'common-ui/src/lib/const-strs' // import { registerForPushNotificationsAsync } from '@/services/notif-service/notif-register' // import { // NotificationProvider, // NotificationContext, // } from '@/services/notif-service/notif-context' // import NotifChecker from '@/services/notif-service/notif-checker' // import NotifRegionSync from '@/src/components/NotifRegionSync' // import { renderWithProviders, flush } from '../helpers/test-utils' // import { resetAllMocks } from '../helpers/reset' // import { // lastProcedureInput, // procedureMutationCalls, // setProcedure, // } from '../mocks/trpc-client' // import { // __configure as configureNotifications, // getExpoPushTokenAsync, // requestPermissionsAsync, // setNotificationChannelAsync, // } from '../mocks/expo-notifications-mock' // import { __setAuthState } from '../mocks/auth-context' // import { AUTH_USER } from '../fixtures' // // /** // * `NotifRegionSync`'s only region dependency. `jest.mock` hoists above the // * imports, but the stub object is read lazily at render time. // */ // const mockUseRegion: { regionId: number | null; bound: { id: number } | null } = { // regionId: null, // bound: null, // } // // jest.mock('@/src/hooks/useRegion', () => ({ // useRegion: () => ({ // region: null, // regionId: mockUseRegion.regionId, // boundId: null, // bound: mockUseRegion.bound, // regionGeneration: 0, // hydrated: true, // coords: null, // locationStatus: 'granted', // isResolvingRegion: false, // setRegion: jest.fn(), // clearRegion: jest.fn(), // refreshLocation: jest.fn(), // }), // })) // // // Deterministic auth for `NotifChecker` (same replacement the README documents). // jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context')) // // const IOS: typeof Platform.OS = 'ios' // // function setPlatform(os: typeof Platform.OS) { // ;(Platform as any).OS = os // } // // function renderChecker(auth: boolean) { // __setAuthState({ // isAuthenticated: auth, // isLoading: false, // user: auth ? AUTH_USER : null, // }) // return renderWithProviders( // // // , // { auth: auth ? 'in' : 'out' } // ) // } // // interface RegionSyncState { // token: string | null // notifPermission: 'pending' | 'granted' | 'denied' // regionId?: number | null // bound?: { id: number } | null // } // // /** Builds a *fresh* element so `rerender` never bails out on identity. */ // function regionSyncElement(state: RegionSyncState) { // mockUseRegion.regionId = state.regionId ?? null // mockUseRegion.bound = state.bound ?? null // return ( // // // // ) // } // // function renderRegionSync(state: RegionSyncState) { // return renderWithProviders(regionSyncElement(state), { auth: false }) // } // // describe('notification helpers', () => { // beforeEach(() => { // resetAllMocks() // }) // // afterEach(() => { // setPlatform(IOS) // }) // // describe('registerForPushNotificationsAsync', () => { // it('NOTIF-01: Android creates the default notification channel', async () => { // setPlatform('android') // // const token = await registerForPushNotificationsAsync() // // expect(setNotificationChannelAsync).toHaveBeenCalledWith( // 'default', // expect.objectContaining({ name: 'default', importance: 5 }) // ) // expect(token).toBe('ExponentPushToken[test-token]') // }) // // it('NOTIF-02: an already granted permission is not re-requested', async () => { // configureNotifications({ permission: 'granted' }) // // const token = await registerForPushNotificationsAsync() // // expect(requestPermissionsAsync).not.toHaveBeenCalled() // expect(getExpoPushTokenAsync).toHaveBeenCalledWith({ projectId: 'test-project-id' }) // expect(token).toBe('ExponentPushToken[test-token]') // }) // // it('NOTIF-03: a permission granted after the request returns the Expo token', async () => { // configureNotifications({ permission: 'undetermined', requestResult: 'granted' }) // // const token = await registerForPushNotificationsAsync() // // expect(requestPermissionsAsync).toHaveBeenCalledTimes(1) // expect(token).toBe('ExponentPushToken[test-token]') // }) // // it('NOTIF-04: a denied permission throws the permission error', async () => { // configureNotifications({ permission: 'denied', requestResult: 'denied' }) // // await expect(registerForPushNotificationsAsync()).rejects.toThrow( // NOTIF_PERMISSION_DENIED // ) // expect(getExpoPushTokenAsync).not.toHaveBeenCalled() // }) // // it('NOTIF-05: a missing project id throws', async () => { // // Freshly required module so the local `expo-constants` stub (no project // // id anywhere) is the one `notif-register` captured. // let isolated: typeof import('@/services/notif-service/notif-register') | undefined // jest.isolateModules(() => { // jest.doMock('expo-constants', () => ({ // __esModule: true, // default: { expoConfig: { extra: {} }, easConfig: {} }, // Constants: { expoConfig: { extra: {} }, easConfig: {} }, // })) // isolated = require('@/services/notif-service/notif-register') // }) // // await expect(isolated!.registerForPushNotificationsAsync()).rejects.toThrow( // 'Project ID not found' // ) // }) // // it('NOTIF-06: a non-physical device throws', async () => { // let isolated: typeof import('@/services/notif-service/notif-register') | undefined // jest.isolateModules(() => { // jest.doMock('expo-device', () => ({ __esModule: true, isDevice: false })) // isolated = require('@/services/notif-service/notif-register') // }) // // await expect(isolated!.registerForPushNotificationsAsync()).rejects.toThrow( // 'Must use physical device for push notifications' // ) // }) // // it('NOTIF-07: a failing getExpoPushToken is wrapped', async () => { // getExpoPushTokenAsync.mockRejectedValueOnce(new Error('token boom')) // // // The wrap replaces the error but keeps its message. // await expect(registerForPushNotificationsAsync()).rejects.toThrow('token boom') // }) // }) // // describe('NotificationProvider / NotifChecker', () => { // it('NOTIFC-01: a granted token is saved through savePushToken', async () => { // renderChecker(true) // // await waitFor(() => // expect(lastProcedureInput('user.user.savePushToken')).toEqual({ // token: 'ExponentPushToken[test-token]', // }) // ) // expect(procedureMutationCalls('user.user.savePushToken')).toHaveLength(1) // }) // // it('NOTIFC-02: a signed-out user still saves the token (current behaviour)', async () => { // // GAP: the effect lists `isAuthenticated` as a dependency but the guard // // never reads it, so the token is posted while signed out too. Pin the // // current behaviour; update when an auth check is added. // renderChecker(false) // // await waitFor(() => // expect(lastProcedureInput('user.user.savePushToken')).toEqual({ // token: 'ExponentPushToken[test-token]', // }) // ) // }) // // it('NOTIFC-03: a denied permission opens the permission dialog', async () => { // configureNotifications({ permission: 'denied', requestResult: 'denied' }) // // const { getByText } = renderChecker(true) // // await waitFor(() => expect(getByText('Notification Permission Denied')).toBeTruthy()) // }) // // it('NOTIFC-04: the Settings button opens the device settings', async () => { // configureNotifications({ permission: 'denied', requestResult: 'denied' }) // const openSettings = jest // .spyOn(Linking, 'openSettings') // .mockImplementation(async () => undefined) // // const { getByText } = renderChecker(true) // await waitFor(() => expect(getByText('Notification Permission Denied')).toBeTruthy()) // // fireEvent.press(getByText('Settings')) // // expect(openSettings).toHaveBeenCalledTimes(1) // }) // // it('NOTIFC-05: Cancel closes the dialog', async () => { // configureNotifications({ permission: 'denied', requestResult: 'denied' }) // // const { getByText, UNSAFE_getByType } = renderChecker(true) // await waitFor(() => expect(UNSAFE_getByType(Modal).props.visible).toBe(true)) // // fireEvent.press(getByText('Cancel')) // // // NOTE: the RN Modal keeps its children mounted on iOS after the first // // show (`isRendered`), so the close state is asserted on the prop, not on // // the copy disappearing. // expect(UNSAFE_getByType(Modal).props.visible).toBe(false) // }) // }) // // describe('NotifRegionSync', () => { // it('NOTIFR-01: no token, no region or a pending permission makes no call', async () => { // const cases: RegionSyncState[] = [ // { token: null, notifPermission: 'granted', regionId: 1 }, // { token: 'tok', notifPermission: 'granted', regionId: null }, // { token: 'tok', notifPermission: 'pending', regionId: 1 }, // ] // // for (const state of cases) { // const view = renderRegionSync(state) // await flush() // expect(procedureMutationCalls('user.user.savePushToken')).toHaveLength(0) // expect(procedureMutationCalls('user.user.recordTrackedRegion')).toHaveLength(0) // view.unmount() // } // }) // // it('NOTIFR-02: a granted token + region saves the token with the region', async () => { // renderRegionSync({ token: 'tok', notifPermission: 'granted', regionId: 1 }) // // await waitFor(() => // expect(lastProcedureInput('user.user.savePushToken')).toEqual({ // token: 'tok', // regionId: 1, // }) // ) // expect(procedureMutationCalls('user.user.recordTrackedRegion')).toHaveLength(0) // }) // // it('NOTIFR-03: a location-derived bound also records the tracked region', async () => { // renderRegionSync({ // token: 'tok', // notifPermission: 'granted', // regionId: 1, // bound: { id: 7 }, // }) // // await waitFor(() => // expect(lastProcedureInput('user.user.recordTrackedRegion')).toEqual({ regionId: 1 }) // ) // expect(lastProcedureInput('user.user.savePushToken')).toEqual({ token: 'tok', regionId: 1 }) // }) // // it('NOTIFR-04: an address-derived region does not record a tracked region', async () => { // renderRegionSync({ token: 'tok', notifPermission: 'granted', regionId: 2, bound: null }) // // await waitFor(() => // expect(lastProcedureInput('user.user.savePushToken')).toEqual({ // token: 'tok', // regionId: 2, // }) // ) // expect(procedureMutationCalls('user.user.recordTrackedRegion')).toHaveLength(0) // }) // // it('NOTIFR-05: the same token/region/source is deduped', async () => { // const view = renderRegionSync({ // token: 'tok', // notifPermission: 'granted', // regionId: 1, // bound: { id: 7 }, // }) // await waitFor(() => expect(procedureMutationCalls('user.user.savePushToken')).toHaveLength(1)) // // // Another location bound for the same region re-runs the effect but keeps // // the (token, region, 'loc') key. // view.rerender( // regionSyncElement({ // token: 'tok', // notifPermission: 'granted', // regionId: 1, // bound: { id: 9 }, // }) // ) // await flush() // // expect(procedureMutationCalls('user.user.savePushToken')).toHaveLength(1) // expect(procedureMutationCalls('user.user.recordTrackedRegion')).toHaveLength(1) // }) // // it('NOTIFR-06: a region change triggers a new sync', async () => { // const view = renderRegionSync({ // token: 'tok', // notifPermission: 'granted', // regionId: 1, // }) // await waitFor(() => expect(procedureMutationCalls('user.user.savePushToken')).toHaveLength(1)) // // view.rerender( // regionSyncElement({ token: 'tok', notifPermission: 'granted', regionId: 2 }) // ) // // await waitFor(() => // expect(procedureMutationCalls('user.user.savePushToken')).toHaveLength(2) // ) // expect(lastProcedureInput('user.user.savePushToken')).toEqual({ token: 'tok', regionId: 2 }) // }) // // it('NOTIFR-07: a failing save is logged and not retried', async () => { // const consoleError = jest.spyOn(console, 'error').mockImplementation(() => undefined) // setProcedure('user.user.savePushToken', { mode: 'error', error: new Error('save boom') }) // // renderRegionSync({ token: 'tok', notifPermission: 'granted', regionId: 1 }) // // await waitFor(() => expect(consoleError).toHaveBeenCalled()) // const logged = consoleError.mock.calls.some((call) => // String(call[0]).includes('[NotifRegionSync] saving the region with the push token failed') // ) // expect(logged).toBe(true) // // // Best-effort telemetry: one attempt, no retry. // await flush(3) // expect(procedureMutationCalls('user.user.savePushToken')).toHaveLength(1) // }) // }) // }) //