/* eslint-disable @typescript-eslint/no-explicit-any */ /** * ROOT-01..ROOT-29 — the app shell (`app/_layout.tsx`) and the wrappers it * composes. * * Rows that need the *whole* provider tree (fonts gate, health gate) mount * `RootLayout`; the remaining rows mount the individual wrapper so their * behaviour is observable without the surrounding noise. */ import React from 'react' import { Alert, BackHandler, Text, View } from 'react-native' import { act, fireEvent, render, waitFor } from '@testing-library/react-native' import { useFonts } from 'expo-font' import * as Updates from 'expo-updates' import * as Linking from 'expo-linking' import Constants from 'expo-constants' import RootLayout from '@/app/_layout' import FirstUserWrapper from '@/components/FirstUserWrapper' import HealthTestWrapper from '@/components/HealthTestWrapper' import WebViewWrapper from '@/components/WebViewWrapper' import UpdateChecker from '@/components/UpdateChecker' import BackHandlerWrapper from '@/components/BackHandler' import { NotificationProvider, useNotification, } from '@/services/notif-service/notif-context' import { renderWithProviders, flush, seedRegion } from '../helpers/test-utils' import { resetAllMocks } from '../helpers/reset' import { setProcedure } from '../mocks/trpc-client' import { CONSTS } from '../fixtures' import { router, __setPathname } from '../mocks/expo-router-mock' import { __configure as configureNotifications, __emitNotification, __emitResponse, getExpoPushTokenAsync, removeNotificationSubscription, } from '../mocks/expo-notifications-mock' import { __set, __snapshot } from '../mocks/secure-store-mock' import { Stack } from '../mocks/expo-router-mock' // `RootLayout` builds its own provider tree against the *real* singleton // QueryClient (default 5-minute gc timers, which keep Jest's event loop alive // long after the suite ends). Swap it for the harness client (gcTime Infinity). jest.mock('@/utils/queryClient', () => ({ __esModule: true, default: require('../helpers/test-utils').createTestQueryClient(), })) // The mocked client above is a single instance for the whole file with // `staleTime: Infinity`, so a successful query from one case would be replayed // to the next (e.g. ROOT-04's failing health check). Reset it per case. const rootQueryClient = require('@/utils/queryClient').default const fontsMock = useFonts as unknown as jest.Mock const SOURCE_VERSION = '1.2.0' function renderHealth(overrides: Record = {}) { seedRegion() setProcedure('common.essentialConsts', { data: { ...CONSTS, ...overrides } }) return renderWithProviders( , { auth: 'out' } ) } function renderUpdateChecker() { seedRegion() return renderWithProviders( , { auth: 'out' } ) } function NotifProbe() { const { expoPushToken, notifPermission, notification } = useNotification() return ( <> {expoPushToken ?? 'no-token'} {notifPermission} {notification ? 'yes' : 'no'} ) } describe('app shell (ROOT-01..ROOT-29)', () => { beforeEach(() => { resetAllMocks() rootQueryClient.clear() fontsMock.mockReturnValue([true, null]) }) it('ROOT-01: an unloaded font set renders nothing', () => { fontsMock.mockReturnValue([false]) const view = render() expect(view.toJSON()).toBeNull() expect(view.queryByTestId('app-root')).toBeNull() }) it('ROOT-02: loaded fonts mount the provider tree and the stack', async () => { seedRegion() __set('isFirstTimeUser', 'false') const view = render() expect(view.getByTestId('app-root')).toBeTruthy() await waitFor(() => expect(view.UNSAFE_getByType(Stack)).toBeTruthy()) }) it('ROOT-03: a pending health check still renders the children', async () => { seedRegion() __set('isFirstTimeUser', 'false') setProcedure('common.healthCheck', { mode: 'pending' }) const view = render() expect(view.getByTestId('app-root')).toBeTruthy() expect(view.queryByText('Service Unavailable')).toBeNull() await flush() }) it('ROOT-04: a failing health check shows Service Unavailable and a Retry action', async () => { seedRegion() setProcedure('common.healthCheck', { mode: 'error', error: new Error('offline') }) const view = render() await waitFor(() => expect(view.getByText('Service Unavailable')).toBeTruthy()) // `refetch` on the tRPC query mock is a bare jest.fn that records nothing, // so the re-request itself cannot be observed here: assert the Retry // control is wired and pressing it does not throw. fireEvent.press(view.getByText('Retry')) expect(view.getByText('Service Unavailable')).toBeTruthy() }) it('ROOT-05: an older build on iOS shows the update dialog and opens the App Store', async () => { const view = renderHealth({ versionNum: '1.3.0' }) await waitFor(() => expect(view.getByText('Update Available')).toBeTruthy()) fireEvent.press(view.getByText('Update Now')) expect(Linking.openURL).toHaveBeenCalledWith(CONSTS.appStoreUrl) }) it('ROOT-06: an older build on Android opens the Play Store', async () => { const previous = require('react-native').Platform.OS require('react-native').Platform.OS = 'android' try { const view = renderHealth({ versionNum: '1.3.0' }) await waitFor(() => expect(view.getByText('Update Available')).toBeTruthy()) fireEvent.press(view.getByText('Update Now')) expect(Linking.openURL).toHaveBeenCalledWith(CONSTS.playStoreUrl) } finally { require('react-native').Platform.OS = previous } }) it('ROOT-07: equal or newer local versions never show the update dialog', async () => { const equal = renderHealth({ versionNum: SOURCE_VERSION }) await flush() expect(equal.queryByText('Update Available')).toBeNull() equal.unmount() const newer = renderHealth({ versionNum: '1.0.0' }) await flush() expect(newer.queryByText('Update Available')).toBeNull() }) it('ROOT-08: a malformed version on either side is ignored without crashing', async () => { const malformedBackend = renderHealth({ versionNum: 'abc.def.ghi' }) await flush() expect(malformedBackend.queryByText('Update Available')).toBeNull() const original = Constants.expoConfig!.version ;(Constants.expoConfig as any).version = 'bad' try { const malformedLocal = renderHealth({ versionNum: '9.9.9' }) await flush() expect(malformedLocal.queryByText('Update Available')).toBeNull() } finally { ;(Constants.expoConfig as any).version = original } }) it('ROOT-09: a first-time user sees the welcome screen and Next stores the flag', async () => { const view = render( ) await waitFor(() => expect(view.getByText('Hello Happy Shopping')).toBeTruthy()) expect(view.queryByTestId('first-user-child')).toBeNull() fireEvent.press(view.getByText('Next')) await waitFor(() => expect(view.getByTestId('first-user-child')).toBeTruthy()) expect(__snapshot().isFirstTimeUser).toBe('false') }) it("ROOT-10: the stored 'false' value renders the children directly", async () => { __set('isFirstTimeUser', 'false') const view = render( ) await waitFor(() => expect(view.getByTestId('first-user-child')).toBeTruthy()) expect(view.queryByText('Hello Happy Shopping')).toBeNull() }) it("ROOT-11: a 'true' or arbitrary stored value keeps the welcome screen", async () => { for (const stored of ['true', 'anything-else']) { __set('isFirstTimeUser', stored) const view = render( ) await waitFor(() => expect(view.getByText('Hello Happy Shopping')).toBeTruthy()) expect(view.queryByTestId('first-user-child')).toBeNull() view.unmount() } }) it('ROOT-12: an absent webviewHtml renders the children', async () => { seedRegion() const view = renderWithProviders( , { auth: 'out' } ) await flush() expect(view.getByTestId('webview-child')).toBeTruthy() expect(view.queryByTestId('webview')).toBeNull() }) it('ROOT-13: a non-closable webview hides the children', async () => { seedRegion() setProcedure('common.essentialConsts', { data: { ...CONSTS, webviewHtml: '

hello

', isWebviewClosable: false }, }) const view = renderWithProviders( , { auth: 'out' } ) await waitFor(() => expect(view.getByTestId('webview')).toBeTruthy()) expect(view.queryByTestId('webview-child')).toBeNull() expect(view.queryByTestId('webview-close')).toBeNull() }) it('ROOT-14: the close button hides a closable webview and reveals the children', async () => { seedRegion() setProcedure('common.essentialConsts', { data: { ...CONSTS, webviewHtml: '

hello

', isWebviewClosable: true }, }) const view = renderWithProviders( , { auth: 'out' } ) await waitFor(() => expect(view.getByTestId('webview-close')).toBeTruthy()) fireEvent.press(view.getByTestId('webview-close')) await waitFor(() => expect(view.getByTestId('webview-child')).toBeTruthy()) expect(view.queryByTestId('webview')).toBeNull() }) it('ROOT-16: a newer backend internal version alerts once and updates', async () => { const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) renderUpdateChecker() setProcedure('common.essentialConsts', { data: { ...CONSTS, internalAppVersion: 5 }, }) await waitFor(() => expect(alertSpy).toHaveBeenCalledTimes(1)) expect(alertSpy.mock.calls[0][0]).toBe('Update available') const buttons = alertSpy.mock.calls[0][2] as any[] const update = buttons.find((button) => button.text === 'Update & Restart') await act(async () => { await update.onPress() }) expect(Updates.fetchUpdateAsync).toHaveBeenCalledTimes(1) expect(Updates.reloadAsync).toHaveBeenCalledTimes(1) expect((Updates.fetchUpdateAsync as jest.Mock).mock.invocationCallOrder[0]).toBeLessThan( (Updates.reloadAsync as jest.Mock).mock.invocationCallOrder[0] ) }) it('ROOT-17: an update fetch failure does not crash or reload', async () => { const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) ;(Updates.fetchUpdateAsync as jest.Mock).mockRejectedValueOnce(new Error('no update')) renderUpdateChecker() setProcedure('common.essentialConsts', { data: { ...CONSTS, internalAppVersion: 5 }, }) await waitFor(() => expect(alertSpy).toHaveBeenCalledTimes(1)) const update = (alertSpy.mock.calls[0][2] as any[]).find( (button) => button.text === 'Update & Restart' ) await act(async () => { await update.onPress() }) expect(Updates.reloadAsync).not.toHaveBeenCalled() }) it('ROOT-18: back on home with an empty stack asks to exit and exits', () => { const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) const exitSpy = jest.spyOn(BackHandler, 'exitApp').mockImplementation(() => undefined) let handler: (() => boolean) | undefined jest .spyOn(BackHandler, 'addEventListener') .mockImplementation((_event: any, listener: any) => { handler = listener return { remove: jest.fn() } }) __setPathname('/home') router.canGoBack.mockReturnValue(false) render() const result = handler!() expect(result).toBe(true) expect(alertSpy).toHaveBeenCalledWith( 'Exit App', 'Are you sure you want to exit?', expect.any(Array) ) const exit = (alertSpy.mock.calls[0][2] as any[]).find((button) => button.text === 'Exit') exit.onPress() expect(exitSpy).toHaveBeenCalledTimes(1) }) it('ROOT-19: back on a non-home route is not intercepted', () => { const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) let handler: (() => boolean) | undefined jest .spyOn(BackHandler, 'addEventListener') .mockImplementation((_event: any, listener: any) => { handler = listener return { remove: jest.fn() } }) __setPathname('/stores') router.canGoBack.mockReturnValue(false) render() expect(handler!()).toBe(false) expect(alertSpy).not.toHaveBeenCalled() }) it('ROOT-20: back while the stack can go back is not intercepted', () => { const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) let handler: (() => boolean) | undefined jest .spyOn(BackHandler, 'addEventListener') .mockImplementation((_event: any, listener: any) => { handler = listener return { remove: jest.fn() } }) __setPathname('/home') router.canGoBack.mockReturnValue(true) render() expect(handler!()).toBe(false) expect(alertSpy).not.toHaveBeenCalled() }) it('ROOT-21: the first-user gate renders nothing while the storage read is pending', () => { const view = render( ) expect(view.toJSON()).toBeNull() }) it('ROOT-22: unmounting the back handler removes its subscription', () => { const remove = jest.fn() jest .spyOn(BackHandler, 'addEventListener') .mockImplementation(() => ({ remove })) __setPathname('/home') router.canGoBack.mockReturnValue(false) const view = render() view.unmount() expect(remove).toHaveBeenCalledTimes(1) }) // it('ROOT-23: a registered push token and granted permission are exposed to children', async () => { // const view = renderWithProviders( // // // , // { auth: false } // ) // // await waitFor(() => // expect(view.getByTestId('notif-token').props.children).toBe( // 'ExponentPushToken[test-token]' // ) // ) // expect(view.getByTestId('notif-permission').props.children).toBe('granted') // }) it('ROOT-24: a permission-denied registration exposes the denied permission', async () => { configureNotifications({ permission: 'denied', requestResult: 'denied' }) const view = renderWithProviders( , { auth: false } ) await waitFor(() => expect(view.getByTestId('notif-permission').props.children).toBe('denied')) }) it('ROOT-25: any other registration failure leaves the permission pending', async () => { getExpoPushTokenAsync.mockRejectedValueOnce(new Error('token boom')) const view = renderWithProviders( , { auth: false } ) await flush(3) expect(view.getByTestId('notif-permission').props.children).toBe('pending') expect(view.getByTestId('notif-token').props.children).toBe('no-token') }) // it('ROOT-26: a foreground notification shows a toast with its title and body', async () => { // const Toast = require('react-native-toast-message').default // const view = renderWithProviders( // // // , // { auth: false } // ) // // await waitFor(() => // expect(view.getByTestId('notif-token').props.children).toBe( // 'ExponentPushToken[test-token]' // ) // ) // // act(() => { // __emitNotification({ // request: { // content: { title: 'New Order', body: 'Your order is confirmed', data: { orderId: 1 } }, // }, // }) // }) // // expect(view.getByTestId('notif-has-notification').props.children).toBe('yes') // expect(Toast.show).toHaveBeenCalledWith( // expect.objectContaining({ text1: 'New Order', text2: 'Your order is confirmed' }) // ) // }) // it('ROOT-27: a notification response carrying doctorId routes home', async () => { // const view = renderWithProviders( // // // , // { auth: false } // ) // await waitFor(() => // expect(view.getByTestId('notif-token').props.children).toBe( // 'ExponentPushToken[test-token]' // ) // ) // // act(() => { // __emitResponse({ // notification: { request: { content: { data: { doctorId: 7 } } } }, // }) // }) // // expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/home') // }) // it('ROOT-28: a notification response carrying tokenId routes home', async () => { // const view = renderWithProviders( // // // , // { auth: false } // ) // await waitFor(() => // expect(view.getByTestId('notif-token').props.children).toBe( // 'ExponentPushToken[test-token]' // ) // ) // // act(() => { // __emitResponse({ // notification: { request: { content: { data: { tokenId: 9 } } } }, // }) // }) // // expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/home') // }) // it('ROOT-29: unmounting the provider removes both notification subscriptions', async () => { // const view = renderWithProviders( // // // , // { auth: false } // ) // await waitFor(() => // expect(view.getByTestId('notif-token').props.children).toBe( // 'ExponentPushToken[test-token]' // ) // ) // // view.unmount() // // expect(removeNotificationSubscription).toHaveBeenCalledTimes(2) // }) })