Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

ReactNativeOnlineDetector.test.ts

396 lines10.9 KB

1import { beforeEach, describe, expect, it, vi } from 'vitest'
2​
3// Import after mocks are set up
4import { AppState } from 'react-native'
5import NetInfo from '@react-native-community/netinfo'
6import { ReactNativeOnlineDetector } from '../src/connectivity/ReactNativeOnlineDetector'
7​
8// Mock the react-native module
9vi.mock(`react-native`, () => {
10 const listeners: Array<(state: string) => void> = []
11 return {
12 AppState: {
13 addEventListener: vi.fn(
14 (event: string, callback: (state: string) => void) => {
15 if (event === `change`) {
16 listeners.push(callback)
17 }
18 return {
19 remove: vi.fn(() => {
20 const index = listeners.indexOf(callback)
21 if (index > -1) {
22 listeners.splice(index, 1)
23 }
24 }),
25 }
26 },
27 ),
28 // Expose for testing
29 __listeners: listeners,
30 __triggerChange: (state: string) => {
31 for (const listener of listeners) {
32 listener(state)
33 }
34 },
35 },
36 }
37})
38​
39// Mock the @react-native-community/netinfo module
40vi.mock(`@react-native-community/netinfo`, () => {
41 type NetworkState = {
42 isConnected: boolean
43 isInternetReachable: boolean | null
44 }
45 const listeners: Array<(state: NetworkState) => void> = []
46 let latestState: NetworkState = {
47 isConnected: true,
48 isInternetReachable: true,
49 }
50 let deliverNextSubscriptionAsync = false
51 return {
52 default: {
53 fetch: vi.fn(() => Promise.resolve(latestState)),
54 addEventListener: vi.fn((callback: (state: NetworkState) => void) => {
55 listeners.push(callback)
56 // NetInfo promises the latest information soon after subscription.
57 const state = latestState
58 if (deliverNextSubscriptionAsync) {
59 deliverNextSubscriptionAsync = false
60 void Promise.resolve().then(() => {
61 if (listeners.includes(callback)) callback(state)
62 })
63 } else callback(state)
64 return () => {
65 const index = listeners.indexOf(callback)
66 if (index > -1) {
67 listeners.splice(index, 1)
68 }
69 }
70 }),
71 __setLatestState: (state: NetworkState) => {
72 latestState = state
73 },
74 __deliverNextSubscriptionAsync: () => {
75 deliverNextSubscriptionAsync = true
76 },
77 __resetSubscriptionDelivery: () => {
78 deliverNextSubscriptionAsync = false
79 },
80 // Expose for testing
81 __listeners: listeners,
82 __triggerState: (state: NetworkState) => {
83 latestState = state
84 for (const listener of listeners) {
85 listener(state)
86 }
87 },
88 },
89 }
90})
91​
92describe(`ReactNativeOnlineDetector`, () => {
93 beforeEach(() => {
94 vi.clearAllMocks()
95 // Clear internal listener arrays
96 ;(AppState as any).__listeners.length = 0
97 ;(NetInfo as any).__listeners.length = 0
98 ;(NetInfo as any).__resetSubscriptionDelivery()
99 ;(NetInfo as any).__setLatestState({
100 isConnected: true,
101 isInternetReachable: true,
102 })
103 })
104​
105 describe(`initialization`, () => {
106 it(`should subscribe to NetInfo on construction`, () => {
107 const detector = new ReactNativeOnlineDetector()
108​
109 expect(NetInfo.addEventListener).toHaveBeenCalledTimes(1)
110 expect(NetInfo.addEventListener).toHaveBeenCalledWith(
111 expect.any(Function),
112 )
113​
114 detector.dispose()
115 })
116​
117 it(`should subscribe to AppState on construction`, () => {
118 const detector = new ReactNativeOnlineDetector()
119​
120 expect(AppState.addEventListener).toHaveBeenCalledTimes(1)
121 expect(AppState.addEventListener).toHaveBeenCalledWith(
122 `change`,
123 expect.any(Function),
124 )
125​
126 detector.dispose()
127 })
128 })
129​
130 describe(`network connectivity changes`, () => {
131 it(`uses the initial state delivered by the network subscription`, () => {
132 ;(NetInfo as any).__setLatestState({
133 isConnected: false,
134 isInternetReachable: false,
135 })
136 const detector = new ReactNativeOnlineDetector()
137 try {
138 expect(detector.isOnline()).toBe(false)
139 expect(NetInfo.fetch).not.toHaveBeenCalled()
140 } finally {
141 detector.dispose()
142 }
143 })
144​
145 it(`does not claim online before the initial subscription state arrives`, async () => {
146 ;(NetInfo as any).__setLatestState({
147 isConnected: false,
148 isInternetReachable: false,
149 })
150 ;(NetInfo as any).__deliverNextSubscriptionAsync()
151 const detector = new ReactNativeOnlineDetector()
152 try {
153 expect(detector.isOnline()).toBe(false)
154 await Promise.resolve()
155 expect(detector.isOnline()).toBe(false)
156 expect(NetInfo.fetch).not.toHaveBeenCalled()
157 } finally {
158 detector.dispose()
159 }
160 })
161​
162 it(`notifies for changes after the subscription's initial state`, () => {
163 ;(NetInfo as any).__setLatestState({
164 isConnected: false,
165 isInternetReachable: false,
166 })
167 const detector = new ReactNativeOnlineDetector()
168 const callback = vi.fn()
169 detector.subscribe(callback)
170 try {
171 ;(NetInfo as any).__triggerState({
172 isConnected: true,
173 isInternetReachable: true,
174 })
175​
176 expect({
177 notifications: callback.mock.calls.length,
178 isOnline: detector.isOnline(),
179 }).toEqual({ notifications: 1, isOnline: true })
180 } finally {
181 detector.dispose()
182 }
183 })
184​
185 it(`should notify subscribers when transitioning from offline to online`, () => {
186 const detector = new ReactNativeOnlineDetector()
187 const callback = vi.fn()
188​
189 detector.subscribe(callback)
190​
191 // First, simulate offline state
192 ;(NetInfo as any).__triggerState({
193 isConnected: false,
194 isInternetReachable: false,
195 })
196​
197 expect(callback).not.toHaveBeenCalled()
198​
199 // Now simulate coming online
200 ;(NetInfo as any).__triggerState({
201 isConnected: true,
202 isInternetReachable: true,
203 })
204​
205 expect(callback).toHaveBeenCalledTimes(1)
206​
207 detector.dispose()
208 })
209​
210 it(`should not notify when already online and staying online`, () => {
211 const detector = new ReactNativeOnlineDetector()
212 const callback = vi.fn()
213​
214 detector.subscribe(callback)
215​
216 // Simulate online state (detector starts assuming online)
217 ;(NetInfo as any).__triggerState({
218 isConnected: true,
219 isInternetReachable: true,
220 })
221​
222 // Should not trigger since we were already considered online
223 expect(callback).not.toHaveBeenCalled()
224​
225 detector.dispose()
226 })
227​
228 it(`should treat isInternetReachable null as potentially reachable`, () => {
229 const detector = new ReactNativeOnlineDetector()
230 const callback = vi.fn()
231​
232 detector.subscribe(callback)
233​
234 // First go offline
235 ;(NetInfo as any).__triggerState({
236 isConnected: false,
237 isInternetReachable: false,
238 })
239​
240 // Now come online with null isInternetReachable (unknown)
241 ;(NetInfo as any).__triggerState({
242 isConnected: true,
243 isInternetReachable: null,
244 })
245​
246 expect(callback).toHaveBeenCalledTimes(1)
247​
248 detector.dispose()
249 })
250 })
251​
252 describe(`app state changes`, () => {
253 it(`should notify subscribers when app becomes active`, () => {
254 const detector = new ReactNativeOnlineDetector()
255 const callback = vi.fn()
256​
257 detector.subscribe(callback)
258​
259 // Simulate app becoming active (foregrounded)
260 ;(AppState as any).__triggerChange(`active`)
261​
262 expect(callback).toHaveBeenCalledTimes(1)
263​
264 detector.dispose()
265 })
266​
267 it(`should not notify when app goes to background`, () => {
268 const detector = new ReactNativeOnlineDetector()
269 const callback = vi.fn()
270​
271 detector.subscribe(callback)
272​
273 // Simulate app going to background
274 ;(AppState as any).__triggerChange(`background`)
275​
276 expect(callback).not.toHaveBeenCalled()
277​
278 detector.dispose()
279 })
280​
281 it(`should not notify when app becomes inactive`, () => {
282 const detector = new ReactNativeOnlineDetector()
283 const callback = vi.fn()
284​
285 detector.subscribe(callback)
286​
287 // Simulate app becoming inactive
288 ;(AppState as any).__triggerChange(`inactive`)
289​
290 expect(callback).not.toHaveBeenCalled()
291​
292 detector.dispose()
293 })
294 })
295​
296 describe(`subscription management`, () => {
297 it(`should support multiple subscribers`, () => {
298 const detector = new ReactNativeOnlineDetector()
299 const callback1 = vi.fn()
300 const callback2 = vi.fn()
301​
302 detector.subscribe(callback1)
303 detector.subscribe(callback2)
304​
305 detector.notifyOnline()
306​
307 expect(callback1).toHaveBeenCalledTimes(1)
308 expect(callback2).toHaveBeenCalledTimes(1)
309​
310 detector.dispose()
311 })
312​
313 it(`should allow unsubscribing`, () => {
314 const detector = new ReactNativeOnlineDetector()
315 const callback = vi.fn()
316​
317 const unsubscribe = detector.subscribe(callback)
318 unsubscribe()
319​
320 detector.notifyOnline()
321​
322 expect(callback).not.toHaveBeenCalled()
323​
324 detector.dispose()
325 })
326​
327 it(`should handle notifyOnline() manual trigger`, () => {
328 const detector = new ReactNativeOnlineDetector()
329 const callback = vi.fn()
330​
331 detector.subscribe(callback)
332​
333 detector.notifyOnline()
334 detector.notifyOnline()
335​
336 expect(callback).toHaveBeenCalledTimes(2)
337​
338 detector.dispose()
339 })
340 })
341​
342 describe(`disposal`, () => {
343 it(`should unsubscribe from all native events on dispose`, () => {
344 const detector = new ReactNativeOnlineDetector()
345 const callback = vi.fn()
346​
347 detector.subscribe(callback)
348 detector.dispose()
349​
350 // NetInfo and AppState listeners should be cleared
351 expect((NetInfo as any).__listeners.length).toBe(0)
352 expect((AppState as any).__listeners.length).toBe(0)
353 })
354​
355 it(`should not notify after dispose`, () => {
356 const detector = new ReactNativeOnlineDetector()
357 const callback = vi.fn()
358​
359 detector.subscribe(callback)
360 detector.dispose()
361​
362 // Try to trigger events - should not notify
363 detector.notifyOnline()
364​
365 expect(callback).not.toHaveBeenCalled()
366 })
367 })
368​
369 describe(`error handling`, () => {
370 it(`should catch and warn on listener errors without stopping other listeners`, () => {
371 const detector = new ReactNativeOnlineDetector()
372 const consoleWarnSpy = vi
373 .spyOn(console, `warn`)
374 .mockImplementation(() => {})
375 const errorCallback = vi.fn(() => {
376 throw new Error(`Test error`)
377 })
378 const successCallback = vi.fn()
379​
380 detector.subscribe(errorCallback)
381 detector.subscribe(successCallback)
382​
383 detector.notifyOnline()
384​
385 expect(errorCallback).toHaveBeenCalledTimes(1)
386 expect(successCallback).toHaveBeenCalledTimes(1)
387 expect(consoleWarnSpy).toHaveBeenCalledWith(
388 `ReactNativeOnlineDetector listener error:`,
389 expect.any(Error),
390 )
391​
392 consoleWarnSpy.mockRestore()
393 detector.dispose()
394 })
395 })
396})