|
| 1 | +import { AppState } from 'react-native' |
| 2 | +import type { AppStateStatus, NativeEventSubscription } from 'react-native' |
| 3 | +import { createMockMMKV } from '../createMMKV/createMockMMKV' |
| 4 | +import { addContentChangedListener } from '../addContentChangedListener/addContentChangedListener' |
| 5 | + |
| 6 | +function mockAppStateChangeListener(): { |
| 7 | + emit: (state: AppStateStatus) => void |
| 8 | +} { |
| 9 | + const listeners = new Set<(state: AppStateStatus) => void>() |
| 10 | + |
| 11 | + jest |
| 12 | + .spyOn(AppState, 'addEventListener') |
| 13 | + .mockImplementation((type, listener): NativeEventSubscription => { |
| 14 | + if (type === 'change') { |
| 15 | + listeners.add(listener as (state: AppStateStatus) => void) |
| 16 | + } |
| 17 | + |
| 18 | + return { |
| 19 | + remove: () => { |
| 20 | + listeners.delete(listener as (state: AppStateStatus) => void) |
| 21 | + }, |
| 22 | + } as NativeEventSubscription |
| 23 | + }) |
| 24 | + |
| 25 | + return { |
| 26 | + emit: (state) => { |
| 27 | + listeners.forEach((listener) => listener(state)) |
| 28 | + }, |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +afterEach(() => { |
| 33 | + jest.clearAllMocks() |
| 34 | + jest.restoreAllMocks() |
| 35 | +}) |
| 36 | + |
| 37 | +test('content changed listener checks content when app becomes active', () => { |
| 38 | + const appState = mockAppStateChangeListener() |
| 39 | + const storage = createMockMMKV({ id: 'content-changed-listener-test' }) |
| 40 | + const checkContentChanged = jest.spyOn(storage, 'checkContentChanged') |
| 41 | + |
| 42 | + addContentChangedListener(storage) |
| 43 | + |
| 44 | + appState.emit('background') |
| 45 | + expect(checkContentChanged).not.toHaveBeenCalled() |
| 46 | + |
| 47 | + appState.emit('active') |
| 48 | + expect(checkContentChanged).toHaveBeenCalledTimes(1) |
| 49 | +}) |
| 50 | + |
| 51 | +test('content changed listener registers once per instance', () => { |
| 52 | + mockAppStateChangeListener() |
| 53 | + const storage = createMockMMKV({ |
| 54 | + id: 'content-changed-listener-once-test', |
| 55 | + }) |
| 56 | + |
| 57 | + addContentChangedListener(storage) |
| 58 | + addContentChangedListener(storage) |
| 59 | + |
| 60 | + expect(AppState.addEventListener).toHaveBeenCalledTimes(1) |
| 61 | +}) |
0 commit comments