|
| 1 | +import {act, renderHook} from '@testing-library/react-hooks' |
| 2 | +import {AppState, AppStateStatus} from 'react-native' |
| 3 | +import {useAppState} from './useAppState' |
| 4 | + |
| 5 | +jest.mock('react-native', () => ({ |
| 6 | + AppState: { |
| 7 | + currentState: 'mock-currentState', |
| 8 | + addEventListener: jest.fn(), |
| 9 | + removeEventListener: jest.fn(), |
| 10 | + }, |
| 11 | +})) |
| 12 | + |
| 13 | +describe('useAppState', () => { |
| 14 | + const addEventListenerMock = AppState.addEventListener as jest.Mock |
| 15 | + const createEmitAppStateChange = () => { |
| 16 | + let listener: (newStatus: AppStateStatus) => {} |
| 17 | + |
| 18 | + addEventListenerMock.mockImplementationOnce((_, fn) => { |
| 19 | + listener = fn |
| 20 | + }) |
| 21 | + |
| 22 | + return (newStatus: AppStateStatus) => listener(newStatus) |
| 23 | + } |
| 24 | + |
| 25 | + it('should return current state by default', () => { |
| 26 | + const {result} = renderHook(() => useAppState()) |
| 27 | + |
| 28 | + expect(result.current).toBe(AppState.currentState) |
| 29 | + }) |
| 30 | + |
| 31 | + it('should update state when it change', () => { |
| 32 | + const newStatus = 'background' |
| 33 | + const emit = createEmitAppStateChange() |
| 34 | + |
| 35 | + const {result} = renderHook(() => useAppState()) |
| 36 | + |
| 37 | + const {current: initialStatus} = result |
| 38 | + |
| 39 | + act(() => { |
| 40 | + emit(newStatus) |
| 41 | + }) |
| 42 | + |
| 43 | + const {current: statusAfterUpdate} = result |
| 44 | + |
| 45 | + expect({initialStatus, statusAfterUpdate}).toEqual({ |
| 46 | + initialStatus: AppState.currentState, |
| 47 | + statusAfterUpdate: newStatus, |
| 48 | + }) |
| 49 | + }) |
| 50 | +}) |
0 commit comments