freshyo/apps/user-ui/tests/mocks/router.ts
2026-09-26 13:41:46 +05:30

68 lines
2.3 KiB
TypeScript

/**
* Shared spies for the mocked expo-router.
*
* The mock lives in each test file rather than in tests/setup.ts: a global mock
* would also apply to tests/home-page/navigation.test.tsx, which needs the real
* router (expo-router/testing-library). Any test file that renders a router
* consumer and is not using the real router must add:
*
* jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
*
* `clearMocks: true` in jest.config.js clears these between tests, but zustand
* stores are not mocks - reset them explicitly where they matter.
*/
import React from 'react'
export const routerMock = {
push: jest.fn(),
replace: jest.fn(),
back: jest.fn(),
navigate: jest.fn(),
canGoBack: jest.fn(() => false),
dismissTo: jest.fn(),
dismissAll: jest.fn(),
setParams: jest.fn(),
}
export function resetRouterMock() {
routerMock.push.mockClear()
routerMock.replace.mockClear()
routerMock.back.mockClear()
routerMock.navigate.mockClear()
}
/**
* Local search params returned by the mocked router. Tests set
* `searchParamsMock.current` before rendering to simulate a route's params.
*/
export const searchParamsMock: { current: Record<string, unknown> } = {
current: {},
}
/** Factory for jest.mock('expo-router', ...). */
export function expoRouterMock() {
return {
useRouter: () => routerMock,
router: routerMock,
usePathname: () => '/',
useLocalSearchParams: () => searchParamsMock.current,
useGlobalSearchParams: () => searchParamsMock.current,
// Run the focus callback once on mount so focus-driven effects (deep-nav
// from home, guards) are exercisable without a real navigator.
useFocusEffect: (callback: () => void | (() => void)) => {
const ran = React.useRef(false)
React.useEffect(() => {
if (ran.current) return
ran.current = true
return callback()
}, [])
},
Link: ({ children }: { children?: unknown }) => children ?? null,
// Layout primitives used by the route files; render children through.
Slot: ({ children }: { children?: unknown }) => children ?? null,
Stack: ({ children }: { children?: unknown }) => children ?? null,
Tabs: ({ children }: { children?: unknown }) => children ?? null,
Redirect: () => null,
}
}