Skip to content

Commit 0b00a5f

Browse files
committed
Add useAppState tests
1 parent 5c8506a commit 0b00a5f

File tree

2 files changed

+54
-4
lines changed

2 files changed

+54
-4
lines changed

src/useAppState.test.ts

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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+
})

src/useAppState.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,11 @@ export function useAppState() {
55
const currentState = AppState.currentState
66
const [appState, setAppState] = useState(currentState)
77

8-
function onChange(newState: AppStateStatus) {
9-
setAppState(newState)
10-
}
11-
128
useEffect(() => {
9+
function onChange(newState: AppStateStatus) {
10+
setAppState(newState)
11+
}
12+
1313
AppState.addEventListener('change', onChange)
1414

1515
return () => {

0 commit comments

Comments
 (0)