-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathNetworkTest.ts
440 lines (365 loc) · 18.2 KB
/
NetworkTest.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
import type {Mock} from 'jest-mock';
import type {OnyxEntry} from 'react-native-onyx';
import MockedOnyx from 'react-native-onyx';
import * as App from '@libs/actions/App';
import {resetReauthentication} from '@libs/Middleware/Reauthentication';
import CONST from '@src/CONST';
import OnyxUpdateManager from '@src/libs/actions/OnyxUpdateManager';
import * as PersistedRequests from '@src/libs/actions/PersistedRequests';
import * as PersonalDetails from '@src/libs/actions/PersonalDetails';
import * as Session from '@src/libs/actions/Session';
import HttpUtils from '@src/libs/HttpUtils';
import Log from '@src/libs/Log';
import * as Network from '@src/libs/Network';
import * as MainQueue from '@src/libs/Network/MainQueue';
import * as NetworkStore from '@src/libs/Network/NetworkStore';
import * as SequentialQueue from '@src/libs/Network/SequentialQueue';
import NetworkConnection from '@src/libs/NetworkConnection';
import ONYXKEYS from '@src/ONYXKEYS';
import type {Session as OnyxSession} from '@src/types/onyx';
import type OnyxNetwork from '@src/types/onyx/Network';
import type ReactNativeOnyxMock from '../../__mocks__/react-native-onyx';
import * as TestHelper from '../utils/TestHelper';
import waitForBatchedUpdates from '../utils/waitForBatchedUpdates';
type OnResolved = (params: {jsonCode?: string | number}) => void;
const Onyx = MockedOnyx as typeof ReactNativeOnyxMock;
jest.mock('@src/libs/Log');
Onyx.init({
keys: ONYXKEYS,
});
OnyxUpdateManager();
const originalXHR = HttpUtils.xhr;
beforeEach(() => {
global.fetch = TestHelper.getGlobalFetchMock();
HttpUtils.xhr = originalXHR;
// Reset any pending requests
MainQueue.clear();
HttpUtils.cancelPendingRequests();
NetworkStore.checkRequiredData();
NetworkStore.setIsAuthenticating(false);
resetReauthentication();
Network.clearProcessQueueInterval();
SequentialQueue.resetQueue();
return Promise.all([SequentialQueue.waitForIdle(), waitForBatchedUpdates(), PersistedRequests.clear(), Onyx.clear()])
.then(() => {
return waitForBatchedUpdates();
})
.then(
() =>
// Wait for all async operations to complete
new Promise((resolve) => {
setTimeout(resolve, 100);
}),
);
});
afterEach(() => {
NetworkStore.resetHasReadRequiredDataFromStorage();
Onyx.addDelayToConnectCallback(0);
jest.clearAllMocks();
});
describe('NetworkTests', () => {
test('failing to reauthenticate should not log out user', () => {
// Given a test user login and account ID
const TEST_USER_LOGIN = 'test@testguy.com';
const TEST_USER_ACCOUNT_ID = 1;
let isOffline: boolean;
Onyx.connect({
key: ONYXKEYS.NETWORK,
callback: (val) => {
isOffline = !!val?.isOffline;
},
});
// Given a test user login and account ID
return TestHelper.signInWithTestUser(TEST_USER_ACCOUNT_ID, TEST_USER_LOGIN).then(() => {
expect(isOffline).toBe(false);
// Mock fetch() so that it throws a TypeError to simulate a bad network connection
global.fetch = jest.fn().mockRejectedValue(new TypeError(CONST.ERROR.FAILED_TO_FETCH));
const actualXhr = HttpUtils.xhr;
const mockedXhr = jest.fn();
mockedXhr
.mockImplementationOnce(() =>
Promise.resolve({
jsonCode: CONST.JSON_CODE.NOT_AUTHENTICATED,
}),
)
// Fail the call to re-authenticate
.mockImplementationOnce(actualXhr)
// The next call should still be using the old authToken
.mockImplementationOnce(() =>
Promise.resolve({
jsonCode: CONST.JSON_CODE.NOT_AUTHENTICATED,
}),
)
// Succeed the call to set a new authToken
.mockImplementationOnce(() =>
Promise.resolve({
jsonCode: CONST.JSON_CODE.SUCCESS,
authToken: 'qwerty12345',
}),
)
// All remaining requests should succeed
.mockImplementation(() =>
Promise.resolve({
jsonCode: CONST.JSON_CODE.SUCCESS,
}),
);
HttpUtils.xhr = mockedXhr;
// This should first trigger re-authentication and then a Failed to fetch
PersonalDetails.openPublicProfilePage(TEST_USER_ACCOUNT_ID);
return waitForBatchedUpdates()
.then(() => Onyx.set(ONYXKEYS.NETWORK, {isOffline: false}))
.then(() => {
expect(isOffline).toBe(false);
// Advance the network request queue by 1 second so that it can realize it's back online
jest.advanceTimersByTime(CONST.NETWORK.PROCESS_REQUEST_DELAY_MS);
return waitForBatchedUpdates();
})
.then(() => {
// Then we will eventually have 1 call to OpenPublicProfilePage and 1 calls to Authenticate
const callsToOpenPublicProfilePage = (HttpUtils.xhr as Mock).mock.calls.filter(([command]) => command === 'OpenPublicProfilePage');
const callsToAuthenticate = (HttpUtils.xhr as Mock).mock.calls.filter(([command]) => command === 'Authenticate');
expect(callsToOpenPublicProfilePage.length).toBe(1);
expect(callsToAuthenticate.length).toBe(1);
});
});
});
test('failing to reauthenticate while offline should not log out user', async () => {
// 1. Setup Phase - Initialize test user and state variables
const TEST_USER_LOGIN = 'test@testguy.com';
const TEST_USER_ACCOUNT_ID = 1;
const defaultTimeout = 1000;
let sessionState: OnyxEntry<OnyxSession>;
let networkState: OnyxEntry<OnyxNetwork>;
// Set up listeners for session and network state changes
Onyx.connect({
key: ONYXKEYS.SESSION,
callback: (val) => (sessionState = val),
});
Onyx.connect({
key: ONYXKEYS.NETWORK,
callback: (val) => (networkState = val),
});
// Sign in test user and wait for updates
await TestHelper.signInWithTestUser(TEST_USER_ACCOUNT_ID, TEST_USER_LOGIN);
await waitForBatchedUpdates();
const initialAuthToken = sessionState?.authToken;
expect(initialAuthToken).toBeDefined();
// 2. Mock Setup Phase - Configure XHR mocks for the test sequence
const mockedXhr = jest
.fn()
// First mock: ReconnectApp will fail with NOT_AUTHENTICATED
.mockImplementationOnce(() =>
Promise.resolve({
jsonCode: CONST.JSON_CODE.NOT_AUTHENTICATED,
}),
)
// Second mock: Authenticate with network check and delay
.mockImplementationOnce(() => {
// Check network state immediately
if (networkState?.isOffline) {
return Promise.reject(new Error('Network request failed'));
}
// create a delayed response. Timeout will expire after the second App.reconnectApp();
return new Promise((_, reject) => {
setTimeout(() => {
reject(new Error('Network request failed'));
}, defaultTimeout);
});
});
HttpUtils.xhr = mockedXhr;
// 3. Test Execution Phase - Start with online network
await Onyx.set(ONYXKEYS.NETWORK, {isOffline: false});
// Trigger reconnect which will fail due to expired token
App.confirmReadyToOpenApp();
App.reconnectApp();
await waitForBatchedUpdates();
// 4. First API Call Verification - Check ReconnectApp
const firstCall = mockedXhr.mock.calls.at(0) as [string, Record<string, unknown>];
expect(firstCall[0]).toBe('ReconnectApp');
// 5. Authentication Start - Verify authenticate was triggered
await waitForBatchedUpdates();
const secondCall = mockedXhr.mock.calls.at(1) as [string, Record<string, unknown>];
expect(secondCall[0]).toBe('Authenticate');
// 6. Network State Change - Set offline and back online while authenticate is pending
await Onyx.set(ONYXKEYS.NETWORK, {isOffline: true});
await Onyx.set(ONYXKEYS.NETWORK, {isOffline: false});
// Trigger another reconnect due to network change
App.confirmReadyToOpenApp();
App.reconnectApp();
await waitForBatchedUpdates();
// 7. Wait and Verify - Wait for authenticate timeout and verify session
await new Promise((resolve) => {
setTimeout(resolve, defaultTimeout + 100);
});
// Verify the session remained intact and wasn't cleared
expect(sessionState?.authToken).toBe(initialAuthToken);
});
test('consecutive API calls eventually succeed when authToken is expired', () => {
// Given a test user login and account ID
const TEST_USER_LOGIN = 'test@testguy.com';
const TEST_USER_ACCOUNT_ID = 1;
const reconnectionCallbacksSpy = jest.spyOn(NetworkConnection, 'triggerReconnectionCallbacks');
expect(reconnectionCallbacksSpy.mock.calls.length).toBe(0);
// When we sign in
return TestHelper.signInWithTestUser(TEST_USER_ACCOUNT_ID, TEST_USER_LOGIN)
.then(() => {
const mockedXhr = jest.fn();
mockedXhr
// And mock the first call to openPublicProfilePage return with an expired session code
.mockImplementationOnce(() =>
Promise.resolve({
jsonCode: CONST.JSON_CODE.NOT_AUTHENTICATED,
}),
)
// The next 2 API calls will also fire and also return a 407
.mockImplementationOnce(() =>
Promise.resolve({
jsonCode: CONST.JSON_CODE.NOT_AUTHENTICATED,
}),
)
.mockImplementationOnce(() =>
Promise.resolve({
jsonCode: CONST.JSON_CODE.NOT_AUTHENTICATED,
}),
)
// The request to Authenticate should succeed and we mock the responses for the remaining calls
.mockImplementationOnce(() =>
Promise.resolve({
jsonCode: CONST.JSON_CODE.SUCCESS,
authToken: 'qwerty12345',
}),
);
HttpUtils.xhr = mockedXhr;
// And then make 3 API READ requests in quick succession with an expired authToken and handle the response
// It doesn't matter which requests these are really as all the response is mocked we just want to see
// that we get re-authenticated
PersonalDetails.openPublicProfilePage(TEST_USER_ACCOUNT_ID);
PersonalDetails.openPublicProfilePage(TEST_USER_ACCOUNT_ID);
PersonalDetails.openPublicProfilePage(TEST_USER_ACCOUNT_ID);
return waitForBatchedUpdates();
})
.then(() => {
// We should expect to see the three calls to OpenApp, but only one call to Authenticate.
// And we should also see the reconnection callbacks triggered.
const callsToopenPublicProfilePage = (HttpUtils.xhr as Mock).mock.calls.filter(([command]) => command === 'OpenPublicProfilePage');
const callsToAuthenticate = (HttpUtils.xhr as Mock).mock.calls.filter(([command]) => command === 'Authenticate');
expect(callsToopenPublicProfilePage.length).toBe(3);
expect(callsToAuthenticate.length).toBe(1);
expect(reconnectionCallbacksSpy.mock.calls.length).toBe(3);
});
});
test('Request will not run until credentials are read from Onyx', () => {
// In order to test an scenario where the auth token and credentials hasn't been read from storage we reset hasReadRequiredDataFromStorage
// and set the session and credentials to "ready" the Network
// Given a test user login and account ID
const TEST_USER_LOGIN = 'test@testguy.com';
// Given a delay to the Onyx.connect callbacks
const ONYX_DELAY_MS = 3000;
Onyx.addDelayToConnectCallback(ONYX_DELAY_MS);
// Given initial state to Network
NetworkStore.resetHasReadRequiredDataFromStorage();
// Given some mock functions to track the isReady
// flag in Network and the http requests made
const spyHttpUtilsXhr = jest.spyOn(HttpUtils, 'xhr').mockImplementation(() => Promise.resolve({}));
// When we make a request
Session.beginSignIn(TEST_USER_LOGIN);
// Then we should expect that no requests have been made yet
expect(spyHttpUtilsXhr).not.toHaveBeenCalled();
// Once credentials are set and we wait for promises to resolve
Onyx.merge(ONYXKEYS.CREDENTIALS, {login: 'test-login'});
Onyx.merge(ONYXKEYS.SESSION, {authToken: 'test-auth-token'});
return waitForBatchedUpdates().then(() => {
// Then we should expect the request to have been made since the network is now ready
expect(spyHttpUtilsXhr).not.toHaveBeenCalled();
});
});
test('Non-retryable request will not be retried if connection is lost in flight', () => {
// Given a xhr mock that will fail as if network connection dropped
const xhr = jest.spyOn(HttpUtils, 'xhr').mockImplementationOnce(() => {
Onyx.merge(ONYXKEYS.NETWORK, {isOffline: true});
return Promise.reject(new Error(CONST.ERROR.FAILED_TO_FETCH));
});
// Given a non-retryable request (that is bound to fail)
const promise = Network.post('Get');
return waitForBatchedUpdates()
.then(() => {
// When network connection is recovered
Onyx.merge(ONYXKEYS.NETWORK, {isOffline: false});
return waitForBatchedUpdates();
})
.then(() => {
// Advance the network request queue by 1 second so that it can realize it's back online
jest.advanceTimersByTime(CONST.NETWORK.PROCESS_REQUEST_DELAY_MS);
return waitForBatchedUpdates();
})
.then(() => {
// Then the request should only have been attempted once and we should get an unable to retry
expect(xhr).toHaveBeenCalledTimes(1);
// And the promise should be resolved with the special offline jsonCode
return expect(promise).resolves.toEqual({jsonCode: CONST.JSON_CODE.UNABLE_TO_RETRY});
});
});
test('test Bad Gateway status will log hmmm', () => {
global.fetch = jest.fn().mockResolvedValueOnce({ok: false, status: CONST.HTTP_STATUS.BAD_GATEWAY, statusText: 'Bad Gateway'});
const logHmmmSpy = jest.spyOn(Log, 'hmmm');
// Given we have a request made while online
return Onyx.set(ONYXKEYS.NETWORK, {isOffline: false})
.then(() => {
Network.post('MockBadNetworkResponse', {param1: 'value1'});
return waitForBatchedUpdates();
})
.then(() => {
expect(logHmmmSpy).toHaveBeenCalled();
});
});
test('test unknown status will log alert', () => {
global.fetch = jest.fn().mockResolvedValueOnce({ok: false, status: 418, statusText: "I'm a teapot"});
const logAlertSpy = jest.spyOn(Log, 'alert');
// Given we have a request made while online
return Onyx.set(ONYXKEYS.NETWORK, {isOffline: false})
.then(() => {
Network.post('MockBadNetworkResponse', {param1: 'value1'});
return waitForBatchedUpdates();
})
.then(() => {
expect(logAlertSpy).toHaveBeenCalled();
});
});
test('test Failed to fetch error for non-retryable requests resolve with unable to retry jsonCode', () => {
// Setup xhr handler that rejects once with a Failed to Fetch
global.fetch = jest.fn().mockRejectedValue(new Error(CONST.ERROR.FAILED_TO_FETCH));
const onResolved = jest.fn() as jest.MockedFunction<OnResolved>;
// Given we have a request made while online
return Onyx.set(ONYXKEYS.NETWORK, {isOffline: false})
.then(() => {
expect(NetworkStore.isOffline()).toBe(false);
// When network calls with are made
Network.post('mock command', {param1: 'value1'}).then(onResolved);
return waitForBatchedUpdates();
})
.then(() => {
const response = onResolved.mock.calls.at(0)?.at(0);
expect(onResolved).toHaveBeenCalled();
expect(response?.jsonCode).toBe(CONST.JSON_CODE.UNABLE_TO_RETRY);
});
});
test('cancelled requests should not be retried', () => {
const xhr = jest.spyOn(HttpUtils, 'xhr');
// GIVEN a mock that will return a "cancelled" request error
global.fetch = jest.fn().mockRejectedValue(new DOMException('Aborted', CONST.ERROR.REQUEST_CANCELLED));
return Onyx.set(ONYXKEYS.NETWORK, {isOffline: false})
.then(() => {
// WHEN we make a few requests and then cancel them
Network.post('MockCommandOne');
Network.post('MockCommandTwo');
Network.post('MockCommandThree');
// WHEN we wait for the requests to all cancel
return waitForBatchedUpdates();
})
.then(() => {
// THEN expect our queue to be empty and for no requests to have been retried
expect(MainQueue.getAll().length).toBe(0);
expect(xhr.mock.calls.length).toBe(3);
});
});
});