|
| 1 | +import { act, fireEvent, render } from '@testing-library/react-native'; |
| 2 | +import { useContext, useState } from 'react'; |
| 3 | +import { TouchableOpacity } from 'react-native'; |
| 4 | + |
| 5 | +import ThemeContextProvider from './ThemeContextProvider'; |
| 6 | +import { ThemeContext } from '../theme'; |
| 7 | +import type { IThemePreference } from '../definitions/ITheme'; |
| 8 | + |
| 9 | +const defaultPrefs: IThemePreference = { currentTheme: 'light', darkLevel: 'dark' }; |
| 10 | +const setTheme = jest.fn(); |
| 11 | + |
| 12 | +function ContextCapture({ onCapture }: { onCapture: (v: object) => void }) { |
| 13 | + const value = useContext(ThemeContext); |
| 14 | + onCapture(value); |
| 15 | + return null; |
| 16 | +} |
| 17 | + |
| 18 | +// Parent holds its own counter state; ThemeContextProvider receives fixed props. |
| 19 | +// This forces ThemeContextProvider to re-render on parent state changes, exercising the |
| 20 | +// useMemo dep-check rather than React's same-props bailout shortcut. |
| 21 | +function ParentWithCounter({ onCapture }: { onCapture: (v: object) => void }) { |
| 22 | + const [count, setCount] = useState(0); |
| 23 | + return ( |
| 24 | + <> |
| 25 | + <ThemeContextProvider theme='light' themePreferences={defaultPrefs} setTheme={setTheme}> |
| 26 | + <ContextCapture onCapture={onCapture} /> |
| 27 | + </ThemeContextProvider> |
| 28 | + <TouchableOpacity testID='bump' onPress={() => setCount(c => c + 1)} accessibilityLabel={String(count)} /> |
| 29 | + </> |
| 30 | + ); |
| 31 | +} |
| 32 | + |
| 33 | +test('value reference is stable across re-renders when theme/prefs unchanged', () => { |
| 34 | + const captured: object[] = []; |
| 35 | + const { getByTestId } = render(<ParentWithCounter onCapture={v => captured.push(v)} />); |
| 36 | + |
| 37 | + act(() => fireEvent.press(getByTestId('bump'))); |
| 38 | + act(() => fireEvent.press(getByTestId('bump'))); |
| 39 | + |
| 40 | + expect(captured.length).toBe(3); |
| 41 | + // All three captures must be the exact same object reference. |
| 42 | + expect(captured[1]).toBe(captured[0]); |
| 43 | + expect(captured[2]).toBe(captured[0]); |
| 44 | +}); |
| 45 | + |
| 46 | +test('value reference changes when theme prop changes', () => { |
| 47 | + const captured: object[] = []; |
| 48 | + const Wrapper = ({ theme }: { theme: 'light' | 'dark' }) => ( |
| 49 | + <ThemeContextProvider theme={theme} themePreferences={defaultPrefs} setTheme={setTheme}> |
| 50 | + <ContextCapture onCapture={v => captured.push(v)} /> |
| 51 | + </ThemeContextProvider> |
| 52 | + ); |
| 53 | + |
| 54 | + const { rerender } = render(<Wrapper theme='light' />); |
| 55 | + rerender(<Wrapper theme='dark' />); |
| 56 | + |
| 57 | + expect(captured.length).toBe(2); |
| 58 | + expect(captured[1]).not.toBe(captured[0]); |
| 59 | + expect(captured[1]).toHaveProperty('theme', 'dark'); |
| 60 | +}); |
0 commit comments