|
| 1 | +import { useState, createContext, useContext, useMemo } from 'react' |
| 2 | +import { renderHook } from 'react-hooks-testing-library' |
| 3 | + |
| 4 | +const DARK: 'dark' = 'dark' |
| 5 | +const LIGHT: 'light' = 'light' |
| 6 | + |
| 7 | +type InitialTheme = typeof DARK | typeof LIGHT | undefined |
| 8 | + |
| 9 | +const themes = { |
| 10 | + light: { primaryLight: '#FFFFFF', primaryDark: '#000000' }, |
| 11 | + dark: { primaryLight: '#000000', primaryDark: '#FFFFFF' } |
| 12 | +} |
| 13 | + |
| 14 | +const ThemesContext = createContext(themes) |
| 15 | + |
| 16 | +const useTheme = (initialTheme: InitialTheme = DARK) => { |
| 17 | + const themes = useContext(ThemesContext) |
| 18 | + const [theme, setTheme] = useState(initialTheme) |
| 19 | + const toggleTheme = () => { |
| 20 | + setTheme(theme === 'light' ? 'dark' : 'light') |
| 21 | + } |
| 22 | + return useMemo(() => ({ ...themes[theme], toggleTheme }), [theme]) |
| 23 | +} |
| 24 | + |
| 25 | +type InitialProps = { initialTheme: InitialTheme } |
| 26 | + |
| 27 | +function checkTypesWithNoInitialProps() { |
| 28 | + const { result, unmount, rerender } = renderHook(() => useTheme()) |
| 29 | + |
| 30 | + // check types |
| 31 | + const _result: { |
| 32 | + current: { |
| 33 | + primaryDark: string |
| 34 | + primaryLight: string |
| 35 | + toggleTheme: () => void |
| 36 | + } |
| 37 | + } = result |
| 38 | + const _unmount: () => boolean = unmount |
| 39 | + const _rerender: () => void = rerender |
| 40 | +} |
| 41 | + |
| 42 | +function checkTypesWithInitialProps() { |
| 43 | + const { result, unmount, rerender } = renderHook( |
| 44 | + ({ initialTheme }: InitialProps) => useTheme(initialTheme), |
| 45 | + { |
| 46 | + initialProps: { initialTheme: DARK } |
| 47 | + } |
| 48 | + ) |
| 49 | + |
| 50 | + // check types |
| 51 | + const _result: { |
| 52 | + current: { |
| 53 | + primaryDark: string |
| 54 | + primaryLight: string |
| 55 | + toggleTheme: () => void |
| 56 | + } |
| 57 | + } = result |
| 58 | + const _unmount: () => boolean = unmount |
| 59 | + const _rerender: (_: InitialProps) => void = rerender |
| 60 | +} |
0 commit comments