-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathjest.setup.js
More file actions
558 lines (508 loc) · 16.8 KB
/
Copy pathjest.setup.js
File metadata and controls
558 lines (508 loc) · 16.8 KB
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
/* eslint-disable @fnando/consistent-import/consistent-import */
/* eslint-disable import/extensions */
import mockClipboard from "@react-native-clipboard/clipboard/jest/clipboard-mock.js";
import mockRNDeviceInfo from "react-native-device-info/jest/react-native-device-info-mock";
import mockGestureHandler from "react-native-gesture-handler/jestSetup";
import { TextEncoder, TextDecoder } from "util";
// Ensure TextEncoder/TextDecoder are available for libs that expect Web APIs
// Node >= 11 provides these in 'util', but they may not be on the global in Jest
// Keep assignments idempotent to avoid warnings across workers
if (typeof global.TextEncoder === "undefined") {
// @ts-expect-error: global typing varies in Jest env
global.TextEncoder = TextEncoder;
}
if (typeof global.TextDecoder === "undefined") {
// @ts-expect-error: global typing varies in Jest env
global.TextDecoder = TextDecoder;
}
// Polyfill TextEncoder for Node.js environment
global.TextEncoder = require("util").TextEncoder;
// Create a direct mock for the specific functions from react-native-responsive-screen
// This ensures these functions are defined before any module imports them
global.heightPercentageToDP = jest.fn((height) => height);
global.widthPercentageToDP = jest.fn((width) => width);
// Mock the module itself
jest.mock("react-native-responsive-screen", () => ({
heightPercentageToDP: global.heightPercentageToDP,
widthPercentageToDP: global.widthPercentageToDP,
}));
// Mock dimensions helper explicitly
jest.mock("helpers/dimensions", () => ({
pxValue: (value) => value,
px: (value) => `${value}px`,
fsValue: (value) => value,
fs: (value) => `${value}px`,
deviceAspectRatio: 0.5,
toPercent: (percentNumber) => `${percentNumber}%`,
calculateEdgeSpacing: (baseSpacing, options) => {
const { multiplier = 1, toNumber = false } = options || {};
const scaledValue = baseSpacing * multiplier;
return toNumber ? scaledValue : `${scaledValue}px`;
},
}));
// Mock react-native
jest.mock("react-native", () => {
const RN = jest.requireActual("react-native");
RN.Dimensions = {
get: jest.fn().mockReturnValue({ width: 400, height: 800 }),
};
RN.Image = {
...RN.Image,
prefetch: jest.fn(() => Promise.resolve(true)),
};
return RN;
});
// Mock navigation
jest.mock("@react-navigation/native", () => {
const originalModule = jest.requireActual("@react-navigation/native");
// Create a mockRef that can be called with generics
const mockRef = {
current: null,
navigate: jest.fn(),
dispatch: jest.fn(),
reset: jest.fn(),
goBack: jest.fn(),
getRootState: jest.fn().mockReturnValue({}),
isFocused: jest.fn().mockReturnValue(true),
canGoBack: jest.fn().mockReturnValue(false),
isReady: jest.fn().mockReturnValue(true),
};
// Mock createNavigationContainerRef as a function that can accept generics
const createNavigationContainerRef = function () {
return mockRef;
};
// Make sure createNavigationContainerRef is available
createNavigationContainerRef.mockRef = mockRef;
return {
__esModule: true,
...originalModule,
useNavigation: jest.fn().mockReturnValue({
navigate: jest.fn(),
replace: jest.fn(),
goBack: jest.fn(),
}),
createNavigationContainerRef,
};
});
// Mock NetInfo
jest.mock("@react-native-community/netinfo", () => ({
addEventListener: jest.fn(() => jest.fn()),
fetch: jest.fn(() =>
Promise.resolve({ isConnected: true, isInternetReachable: true }),
),
}));
// Mock safe area context
jest.mock("react-native-safe-area-context", () => {
const inset = {
top: 0,
right: 0,
bottom: 0,
left: 0,
};
return {
SafeAreaProvider: jest.fn(({ children }) => children),
useSafeAreaInsets: jest.fn(() => inset),
};
});
jest.mock("@react-native-clipboard/clipboard", () => mockClipboard);
jest.mock("@stablelib/base64", () => ({
encode: jest.fn((input) => `mock-base64(${input})`),
decode: jest.fn((input) => new Uint8Array([1, 2, 3])), // Mock decoded Uint8Array
}));
jest.mock("@stablelib/utf8", () => ({
encode: jest.fn(
(input) => new Uint8Array(input.split("").map((c) => c.charCodeAt(0))),
),
decode: jest.fn((input) => "mock-decoded-text"),
}));
jest.mock("config/logger", () => ({
logger: {
error: jest.fn(),
info: jest.fn(),
warn: jest.fn(),
debug: jest.fn(),
},
MAX_RECURSIVE_DEPTH: 8,
MAX_DEPTH_SENTINEL: "[MAX_DEPTH_EXCEEDED]",
}));
jest.mock("react-native-scrypt", () => {
return jest.fn(() => Promise.resolve("a1b2c3d4")); // Mocked hex string
});
jest.mock("tweetnacl", () => {
const secretbox = {
keyLength: 32,
nonceLength: 24,
open: jest.fn(() => new Uint8Array([77, 111, 99, 107])),
};
return {
secretbox,
randomBytes: jest.fn((length) => new Uint8Array(length).fill(1)),
};
});
jest.mock("@react-native-async-storage/async-storage", () =>
require("@react-native-async-storage/async-storage/jest/async-storage-mock"),
);
jest.mock("helpers/localeUtils", () => ({
getDeviceLanguage: jest.fn().mockReturnValue("en"),
isSupportedLanguage: jest.fn().mockReturnValue(true),
}));
// Mock stellarExpert service to avoid import issues
jest.mock("services/stellarExpert", () => ({
searchToken: jest.fn(async () => ({
_embedded: {
records: [],
},
})),
}));
// Mock react-native-bootsplash
jest.mock("react-native-bootsplash", () => ({
hide: jest.fn(),
show: jest.fn(),
getVisibilityStatus: jest.fn(() => Promise.resolve("hidden")),
}));
jest.mock("@react-navigation/native-stack", () => ({
createNativeStackNavigator: () => ({
Navigator: jest.fn(({ children }) => children),
Screen: jest.fn(),
Group: jest.fn(),
}),
}));
jest.mock("@react-navigation/bottom-tabs", () => ({
createBottomTabNavigator: () => ({
Navigator: jest.fn(({ children }) => children),
Screen: jest.fn(),
Group: jest.fn(),
}),
}));
jest.mock("react-native-device-info", () => mockRNDeviceInfo);
jest.mock("react-native-gesture-handler", () => mockGestureHandler);
jest.mock("@gorhom/bottom-sheet", () => {
const mockBottomSheet = {
present: jest.fn(),
dismiss: jest.fn(),
snapToIndex: jest.fn(),
expand: jest.fn(),
collapse: jest.fn(),
close: jest.fn(),
};
return {
__esModule: true,
...jest.requireActual("@gorhom/bottom-sheet"),
useBottomSheetModal: () => mockBottomSheet,
useBottomSheet: () => mockBottomSheet,
};
});
jest.mock("react-native-vision-camera", () => ({
Camera: "Camera",
useCameraDevice: () => null,
useCodeScanner: () => ({}),
useCameraPermission: () => ({
hasPermission: false,
requestPermission: jest.fn(),
}),
}));
jest.mock("zeego/dropdown-menu");
jest.mock("ducks/walletKit", () => ({
WalletKitEventTypes: {
SESSION_PROPOSAL: "SESSION_PROPOSAL",
SESSION_REQUEST: "SESSION_REQUEST",
NONE: "NONE",
},
StellarRpcMethods: {
SIGN_XDR: "SIGN_XDR",
SIGN_AND_SUBMIT_XDR: "SIGN_AND_SUBMIT_XDR",
},
StellarRpcChains: {
PUBLIC: "PUBLIC",
TESTNET: "TESTNET",
},
StellarRpcEvents: {
ACCOUNT_CHANGED: "ACCOUNT_CHANGED",
},
useWalletKitStore: () => ({
event: {},
activeSessions: [],
setEvent: jest.fn(),
clearEvent: jest.fn(),
fetchActiveSessions: jest.fn(),
disconnectAllSessions: jest.fn(),
}),
}));
jest.mock("services/analytics", () => ({
analytics: {
track: jest.fn(),
trackAppOpened: jest.fn(),
setAnalyticsEnabled: jest.fn(),
identifyUser: jest.fn(),
trackReAuthSuccess: jest.fn(),
trackReAuthFail: jest.fn(),
trackSignedTransaction: jest.fn(),
trackSimulationError: jest.fn(),
trackCopyPublicKey: jest.fn(),
trackSendPaymentSuccess: jest.fn(),
trackSendPaymentPathPaymentSuccess: jest.fn(),
trackSwapSuccess: jest.fn(),
trackTransactionError: jest.fn(),
trackSendPaymentSetMax: jest.fn(),
trackSendPaymentTypeSelected: jest.fn(),
trackCopyBackupPhrase: jest.fn(),
trackQRScanSuccess: jest.fn(),
trackQRScanError: jest.fn(),
},
TransactionType: {
Classic: "classic",
Soroban: "soroban",
},
}));
jest.mock("services/analytics/core", () => ({
initAnalytics: jest.fn(),
setAnalyticsEnabled: jest.fn(),
track: jest.fn(),
flushEvents: jest.fn(),
trackAppOpened: jest.fn(),
flushOnBackground: jest.fn(),
isInitialized: jest.fn(() => false),
}));
jest.mock("services/analytics/user", () => ({
identifyUser: jest.fn(),
getUserId: jest.fn(() => Promise.resolve("test-user-id")),
}));
jest.mock("react-native-permissions", () => ({
PERMISSIONS: {
IOS: {
APP_TRACKING_TRANSPARENCY: "app-tracking-transparency",
},
ANDROID: {
READ_MEDIA_IMAGES: "android.permission.READ_MEDIA_IMAGES",
READ_MEDIA_VIDEO: "android.permission.READ_MEDIA_VIDEO",
READ_EXTERNAL_STORAGE: "android.permission.READ_EXTERNAL_STORAGE",
},
},
RESULTS: {
GRANTED: "granted",
DENIED: "denied",
BLOCKED: "blocked",
UNAVAILABLE: "unavailable",
},
check: jest.fn(() => Promise.resolve("granted")),
request: jest.fn(() => Promise.resolve("granted")),
checkMultiple: jest.fn(() =>
Promise.resolve(["granted", "granted", "granted"]),
),
requestMultiple: jest.fn(() =>
Promise.resolve(["granted", "granted", "granted"]),
),
openSettings: jest.fn(() => Promise.resolve()),
}));
jest.mock("@react-native-camera-roll/camera-roll", () => ({
CameraRoll: {
saveAsset: jest.fn(() => Promise.resolve()),
getPhotos: jest.fn(() => Promise.resolve({ edges: [] })),
deletePhotos: jest.fn(() => Promise.resolve()),
},
}));
jest.mock("@dr.pogodin/react-native-fs", () => ({
DocumentDirectoryPath: "/mock/documents/path",
downloadFile: jest.fn(() => ({
promise: Promise.resolve({ statusCode: 200 }),
})),
exists: jest.fn(() => Promise.resolve(true)),
unlink: jest.fn(() => Promise.resolve()),
}));
// Mock react-native-biometrics
jest.mock("react-native-biometrics", () => ({
__esModule: true,
default: jest.fn().mockImplementation(() => ({
isSensorAvailable: jest.fn(() => Promise.resolve(true)),
simplePrompt: jest.fn(() => Promise.resolve({ success: true })),
createKeys: jest.fn(() =>
Promise.resolve({ publicKey: "mock-public-key" }),
),
deleteKeys: jest.fn(() => Promise.resolve()),
createSignature: jest.fn(() =>
Promise.resolve({ signature: "mock-signature" }),
),
biometricKeysExist: jest.fn(() => Promise.resolve(true)),
})),
}));
// Mock the useBiometrics hook
jest.mock("hooks/useBiometrics", () => ({
useBiometrics: jest.fn(() => ({
biometryType: null,
setIsBiometricsEnabled: jest.fn(),
isBiometricsEnabled: false,
enableBiometrics: jest.fn(() => Promise.resolve(true)),
disableBiometrics: jest.fn(() => Promise.resolve(true)),
checkBiometrics: jest.fn(() => Promise.resolve(null)),
handleEnableBiometrics: jest.fn(() => Promise.resolve(true)),
handleDisableBiometrics: jest.fn(() => Promise.resolve(true)),
verifyBiometrics: jest.fn(() => Promise.resolve(true)),
getButtonIcon: jest.fn(() => null),
getButtonText: jest.fn(() => ""),
getButtonColor: jest.fn(() => "#000000"),
getBiometricButtonIcon: jest.fn(() => null),
})),
}));
jest.mock("react-native-keychain", () => ({
BIOMETRY_TYPE: {
FACE_ID: "FaceID",
TOUCH_ID: "TouchID",
FINGERPRINT: "Fingerprint",
FACE: "Face",
IRIS: "Iris",
NONE: "None",
},
ACCESSIBLE: {
ALWAYS_THIS_DEVICE_ONLY: "AccessibleAlwaysThisDeviceOnly",
ALWAYS: "AccessibleAlways",
WHEN_UNLOCKED_THIS_DEVICE_ONLY: "AccessibleWhenUnlockedThisDeviceOnly",
WHEN_UNLOCKED: "AccessibleWhenUnlocked",
AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY:
"AccessibleAfterFirstUnlockThisDeviceOnly",
AFTER_FIRST_UNLOCK: "AccessibleAfterFirstUnlock",
WHEN_PASSCODE_SET_THIS_DEVICE_ONLY:
"AccessibleWhenPasscodeSetThisDeviceOnly",
WHEN_PASSCODE_SET: "AccessibleWhenPasscodeSet",
},
ACCESS_CONTROL: {
USER_PRESENCE: "UserPresence",
BIOMETRY_ANY: "BiometryAny",
BIOMETRY_CURRENT_SET: "BiometryCurrentSet",
DEVICE_PASSCODE: "DevicePasscode",
WATCH: "Watch",
OR: "Or",
AND: "And",
},
AUTHENTICATION_TYPE: {
BIOMETRICS: "AuthenticationWithBiometrics",
DEVICE_PASSCODE_OR_BIOMETRICS:
"AuthenticationWithDevicePasscodeOrBiometrics",
DEVICE_PASSCODE: "AuthenticationWithDevicePasscode",
},
SECURITY_LEVEL: {
ANY: "SecurityLevelAny",
SECURE_SOFTWARE: "SecurityLevelSecureSoftware",
SECURE_HARDWARE: "SecurityLevelSecureHardware",
},
getSupportedBiometryType: jest.fn(() => Promise.resolve(null)),
getInternetCredentials: jest.fn(() => Promise.resolve(null)),
setInternetCredentials: jest.fn(() => Promise.resolve()),
resetInternetCredentials: jest.fn(() => Promise.resolve()),
getGenericPassword: jest.fn(() => Promise.resolve(null)),
setGenericPassword: jest.fn(() => Promise.resolve()),
resetGenericPassword: jest.fn(() => Promise.resolve()),
hasGenericPassword: jest.fn(() => Promise.resolve(false)),
getAllGenericPasswordServices: jest.fn(() => Promise.resolve([])),
getAllInternetCredentials: jest.fn(() => Promise.resolve([])),
canImplyAuthentication: jest.fn(() => Promise.resolve(false)),
getSecurityLevel: jest.fn(() => Promise.resolve("SecurityLevelAny")),
getAvailableBiometryType: jest.fn(() => Promise.resolve("FaceID")),
isSensorAvailable: jest.fn(() => Promise.resolve(true)),
}));
// Mock react-native-quick-crypto (native AES-GCM — not available in Node/Jest)
jest.mock("react-native-quick-crypto", () => ({
__esModule: true,
default: {
getRandomValues: jest.fn((arr) => arr),
subtle: {
importKey: jest.fn(() => Promise.resolve({ type: "secret" })),
encrypt: jest.fn(() => Promise.resolve(new ArrayBuffer(32))),
decrypt: jest.fn(() => Promise.resolve(new ArrayBuffer(32))),
exportKey: jest.fn(() => Promise.resolve(new ArrayBuffer(32))),
},
},
}));
jest.mock("hooks/useGetActiveAccount", () => ({
__esModule: true,
default: jest.fn(() => ({
account: {
publicKey: "GAZAJVMMEWVIQRP6RXQYTVAITE7SC2CBHALQTVW2N4DYBYPWZUH5VJGG",
privateKey: "mock-private-key",
accountName: "Test Account",
id: "test-account-id",
subentryCount: 0,
},
isLoading: false,
error: null,
refreshAccount: jest.fn(),
signTransaction: jest.fn(),
})),
}));
jest.mock("hooks/useBalancesList", () => ({
useBalancesList: jest.fn(() => ({
balanceItems: [],
scanResults: {},
isLoading: false,
error: null,
noBalances: true,
isRefreshing: false,
isFunded: false,
handleRefresh: jest.fn(),
})),
}));
jest.mock("hooks/useWelcomeBanner", () => ({
useWelcomeBanner: jest.fn(() => ({
welcomeBannerBottomSheetModalRef: { current: null },
handleWelcomeBannerDismiss: jest.fn(),
})),
}));
// Mock Sentry for Jest tests
jest.mock("@sentry/react-native", () => ({
init: jest.fn(),
captureException: jest.fn(),
captureMessage: jest.fn(),
addBreadcrumb: jest.fn(),
setContext: jest.fn(),
setUser: jest.fn(),
setTag: jest.fn(),
setExtra: jest.fn(),
wrap: jest.fn((component) => component), // Return component as-is for testing
}));
// Mock react-native-localize
const mockGetNumberFormatSettings = jest.fn(() => ({
decimalSeparator: ".",
groupingSeparator: ",",
}));
jest.mock("react-native-localize", () => ({
getNumberFormatSettings: mockGetNumberFormatSettings,
getLocales: jest.fn(() => [
{
countryCode: "US",
languageTag: "en-US",
languageCode: "en",
isRTL: false,
},
]),
getCurrencies: jest.fn(() => ["USD"]),
getTimeZone: jest.fn(() => "America/New_York"),
uses24HourClock: jest.fn(() => false),
usesMetricSystem: jest.fn(() => false),
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
}));
// Export the mock function so tests can modify it
global.mockGetNumberFormatSettings = mockGetNumberFormatSettings;
// Mock config/envConfig to avoid async initialization issues in tests
jest.mock("config/envConfig", () => ({
EnvConfig: {
AMPLITUDE_API_KEY: "mock-amplitude-key",
AMPLITUDE_EXPERIMENT_DEPLOYMENT_KEY: "mock-experiment-key",
SENTRY_DSN: "mock-sentry-dsn",
WALLET_KIT_PROJECT_ID: "mock-wallet-kit-project-id",
WALLET_KIT_MT_URL: "https://mock-wallet-kit.example.com",
WALLET_KIT_MT_ICON: "https://mock-icon.example.com/icon.png",
WALLET_KIT_MT_NAME: "Mock Freighter Wallet",
WALLET_KIT_MT_DESCRIPTION: "Mock wallet description",
WALLET_KIT_MT_REDIRECT_NATIVE: "mockfreighter://",
ANDROID_DEBUG_KEYSTORE_PASSWORD: "mock-debug-password",
ANDROID_DEBUG_KEYSTORE_ALIAS: "mock-debug-alias",
ANDROID_DEV_KEYSTORE_PASSWORD: "mock-dev-password",
ANDROID_DEV_KEYSTORE_ALIAS: "mock-dev-alias",
ANDROID_PROD_KEYSTORE_PASSWORD: "mock-prod-password",
ANDROID_PROD_KEYSTORE_ALIAS: "mock-prod-alias",
},
BackendEnvConfig: {
FREIGHTER_BACKEND_V1_URL: "https://mock-backend-v1-dev.example.com/api/v1",
FREIGHTER_BACKEND_V2_URL: "https://mock-backend-v2-dev.example.com/api/v1",
},
}));