-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFormoAnalytics.test.ts
More file actions
456 lines (360 loc) · 13.3 KB
/
FormoAnalytics.test.ts
File metadata and controls
456 lines (360 loc) · 13.3 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
import { SignatureStatus, TransactionStatus } from '../types';
// Mock instances that persist across tests
const mockStorageInstance = {
get: jest.fn(),
set: jest.fn(),
remove: jest.fn(),
isAvailable: jest.fn(),
};
const mockStorageManager = {
initialize: jest.fn(),
getPrimaryStorage: jest.fn(),
getStorage: jest.fn(),
};
const mockEventManager = {
addEvent: jest.fn(),
};
const mockEventQueue = {
flush: jest.fn(),
clear: jest.fn(),
cleanup: jest.fn(),
};
const mockSession = {
isWalletDetected: jest.fn(),
isWalletIdentified: jest.fn(),
markWalletDetected: jest.fn(),
markWalletIdentified: jest.fn(),
clear: jest.fn(),
};
// Mock dependencies
jest.mock('../lib/storage', () => ({
__esModule: true,
initStorageManager: jest.fn(),
storage: jest.fn(),
getStorageManager: jest.fn(),
}));
jest.mock('../lib/event', () => ({
__esModule: true,
EventManager: jest.fn(),
EventQueue: jest.fn(),
}));
jest.mock('../lib/session', () => ({
__esModule: true,
FormoAnalyticsSession: jest.fn(),
}));
jest.mock('../lib/consent', () => ({
__esModule: true,
setConsentFlag: jest.fn(),
getConsentFlag: jest.fn(),
removeConsentFlag: jest.fn(),
}));
const mockLifecycleManager = {
start: jest.fn(),
cleanup: jest.fn(),
};
jest.mock('../lib/lifecycle', () => ({
__esModule: true,
AppLifecycleManager: jest.fn(),
}));
jest.mock('../lib/logger', () => ({
__esModule: true,
logger: {
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
debug: jest.fn(),
log: jest.fn(),
},
Logger: {
init: jest.fn(),
},
}));
// Import after mocking
import { FormoAnalytics } from '../FormoAnalytics';
import { initStorageManager, storage } from '../lib/storage';
import { EventManager, EventQueue } from '../lib/event';
import { FormoAnalyticsSession } from '../lib/session';
import { setConsentFlag, getConsentFlag, removeConsentFlag } from '../lib/consent';
import { AppLifecycleManager } from '../lib/lifecycle';
// Helper to setup all mock implementations
const setupMocks = () => {
// Storage mocks
mockStorageInstance.get.mockReturnValue(null);
mockStorageInstance.set.mockReturnValue(undefined);
mockStorageInstance.remove.mockReturnValue(undefined);
mockStorageInstance.isAvailable.mockReturnValue(true);
mockStorageManager.initialize.mockResolvedValue(undefined);
mockStorageManager.getPrimaryStorage.mockReturnValue(mockStorageInstance);
mockStorageManager.getStorage.mockReturnValue(mockStorageInstance);
(initStorageManager as jest.Mock).mockReturnValue(mockStorageManager);
(storage as jest.Mock).mockReturnValue(mockStorageInstance);
// Event mocks
mockEventManager.addEvent.mockResolvedValue(undefined);
mockEventQueue.flush.mockResolvedValue(undefined);
mockEventQueue.clear.mockReturnValue(undefined);
mockEventQueue.cleanup.mockResolvedValue(undefined);
(EventManager as jest.Mock).mockImplementation(() => mockEventManager);
(EventQueue as jest.Mock).mockImplementation(() => mockEventQueue);
// Session mocks
mockSession.isWalletDetected.mockReturnValue(false);
mockSession.isWalletIdentified.mockReturnValue(false);
mockSession.markWalletDetected.mockReturnValue(undefined);
mockSession.markWalletIdentified.mockReturnValue(undefined);
mockSession.clear.mockReturnValue(undefined);
(FormoAnalyticsSession as jest.Mock).mockImplementation(() => mockSession);
// Consent mocks
(getConsentFlag as jest.Mock).mockReturnValue(null);
// Lifecycle mocks
mockLifecycleManager.start.mockResolvedValue(undefined);
mockLifecycleManager.cleanup.mockReturnValue(undefined);
(AppLifecycleManager as jest.Mock).mockImplementation(() => mockLifecycleManager);
};
describe('FormoAnalytics', () => {
let analytics: FormoAnalytics;
const writeKey = 'test-write-key';
beforeEach(async () => {
// Re-setup mock implementations after clearMocks
setupMocks();
analytics = await FormoAnalytics.init(writeKey);
});
describe('init()', () => {
it('should initialize with writeKey', async () => {
const instance = await FormoAnalytics.init('my-key');
expect(instance.config.writeKey).toBe('my-key');
});
it('should call initStorageManager with writeKey', async () => {
await FormoAnalytics.init('my-key');
expect(initStorageManager).toHaveBeenCalledWith('my-key');
});
it('should call ready callback if provided', async () => {
const readyCallback = jest.fn();
await FormoAnalytics.init('my-key', { ready: readyCallback });
expect(readyCallback).toHaveBeenCalled();
});
it('should initialize storage with asyncStorage if provided', async () => {
const mockAsyncStorage = {
getItem: jest.fn(),
setItem: jest.fn(),
removeItem: jest.fn(),
};
await FormoAnalytics.init('my-key', {}, mockAsyncStorage as any);
expect(mockStorageManager.initialize).toHaveBeenCalledWith(mockAsyncStorage);
});
});
describe('connect()', () => {
it('should not track if chainId is null', async () => {
await analytics.connect({ chainId: null as any, address: '0x742d35cc6634c0532925a3b844bc9e7595f3f6d2' });
expect(mockEventManager.addEvent).not.toHaveBeenCalled();
});
it('should not track if chainId is 0', async () => {
await analytics.connect({ chainId: 0, address: '0x742d35cc6634c0532925a3b844bc9e7595f3f6d2' });
expect(mockEventManager.addEvent).not.toHaveBeenCalled();
});
it('should not track if address is empty', async () => {
await analytics.connect({ chainId: 1, address: '' });
expect(mockEventManager.addEvent).not.toHaveBeenCalled();
});
it('should not track if address is invalid', async () => {
await analytics.connect({ chainId: 1, address: 'invalid-address' });
expect(mockEventManager.addEvent).not.toHaveBeenCalled();
});
it('should track valid connect event', async () => {
await analytics.connect({
chainId: 1,
address: '0x742d35cc6634c0532925a3b844bc9e7595f3f6d2',
});
expect(mockEventManager.addEvent).toHaveBeenCalled();
});
it('should update currentChainId and currentAddress after connect', async () => {
await analytics.connect({
chainId: 1,
address: '0x742d35cc6634c0532925a3b844bc9e7595f3f6d2',
});
expect(analytics.currentChainId).toBe(1);
expect(analytics.currentAddress).toBeDefined();
});
});
describe('disconnect()', () => {
it('should track disconnect event', async () => {
await analytics.disconnect();
expect(mockEventManager.addEvent).toHaveBeenCalled();
});
it('should clear currentAddress and currentChainId after disconnect', async () => {
analytics.currentChainId = 1;
analytics.currentAddress = '0x742d35cc6634c0532925a3b844bc9e7595f3f6d2';
await analytics.disconnect();
expect(analytics.currentChainId).toBeUndefined();
expect(analytics.currentAddress).toBeUndefined();
});
});
describe('chain()', () => {
beforeEach(async () => {
// Set up a connected state
analytics.currentAddress = '0x742d35cc6634c0532925a3b844bc9e7595f3f6d2';
analytics.currentChainId = 1;
});
it('should not track if chainId is empty', async () => {
await analytics.chain({ chainId: 0 });
expect(mockEventManager.addEvent).not.toHaveBeenCalled();
});
it('should not track if chainId is invalid', async () => {
await analytics.chain({ chainId: NaN });
expect(mockEventManager.addEvent).not.toHaveBeenCalled();
});
it('should not track if no address is available', async () => {
analytics.currentAddress = undefined;
await analytics.chain({ chainId: 137 });
expect(mockEventManager.addEvent).not.toHaveBeenCalled();
});
it('should track valid chain change event', async () => {
await analytics.chain({ chainId: 137 });
expect(mockEventManager.addEvent).toHaveBeenCalled();
});
it('should update currentChainId after chain change', async () => {
await analytics.chain({ chainId: 137 });
expect(analytics.currentChainId).toBe(137);
});
});
describe('signature()', () => {
it('should track signature with chainId 0 (chainId is optional)', async () => {
await analytics.signature({
status: SignatureStatus.REQUESTED,
chainId: 0,
address: '0x742d35cc6634c0532925a3b844bc9e7595f3f6d2',
message: 'test message',
});
expect(mockEventManager.addEvent).toHaveBeenCalled();
});
it('should track signature without chainId', async () => {
await analytics.signature({
status: SignatureStatus.REQUESTED,
address: '0x742d35cc6634c0532925a3b844bc9e7595f3f6d2',
message: 'test message',
});
expect(mockEventManager.addEvent).toHaveBeenCalled();
});
it('should not track if address is empty', async () => {
await analytics.signature({
status: SignatureStatus.REQUESTED,
chainId: 1,
address: '',
message: 'test message',
});
expect(mockEventManager.addEvent).not.toHaveBeenCalled();
});
it('should track valid signature event', async () => {
await analytics.signature({
status: SignatureStatus.CONFIRMED,
chainId: 1,
address: '0x742d35cc6634c0532925a3b844bc9e7595f3f6d2',
message: 'test message',
signatureHash: '0xabc123',
});
expect(mockEventManager.addEvent).toHaveBeenCalled();
});
});
describe('transaction()', () => {
it('should not track if chainId is invalid', async () => {
await analytics.transaction({
status: TransactionStatus.STARTED,
chainId: 0,
address: '0x742d35cc6634c0532925a3b844bc9e7595f3f6d2',
});
expect(mockEventManager.addEvent).not.toHaveBeenCalled();
});
it('should not track if address is empty', async () => {
await analytics.transaction({
status: TransactionStatus.STARTED,
chainId: 1,
address: '',
});
expect(mockEventManager.addEvent).not.toHaveBeenCalled();
});
it('should track valid transaction event', async () => {
await analytics.transaction({
status: TransactionStatus.CONFIRMED,
chainId: 1,
address: '0x742d35cc6634c0532925a3b844bc9e7595f3f6d2',
transactionHash: '0xdef456',
value: '1000000000000000000',
});
expect(mockEventManager.addEvent).toHaveBeenCalled();
});
});
describe('track()', () => {
it('should track custom events', async () => {
await analytics.track('button_click', { button_id: 'submit' });
expect(mockEventManager.addEvent).toHaveBeenCalled();
});
});
describe('screen()', () => {
it('should track screen views', async () => {
await analytics.screen('HomeScreen', undefined, { section: 'featured' });
expect(mockEventManager.addEvent).toHaveBeenCalled();
});
});
describe('opt-out tracking', () => {
it('should return false for hasOptedOutTracking by default', () => {
expect(analytics.hasOptedOutTracking()).toBe(false);
});
it('should set opt-out flag when optOutTracking is called', async () => {
analytics.optOutTracking();
expect(setConsentFlag).toHaveBeenCalled();
});
it('should remove opt-out flag when optInTracking is called', () => {
analytics.optInTracking();
expect(removeConsentFlag).toHaveBeenCalled();
});
});
describe('isAutocaptureEnabled()', () => {
it('should return true by default', () => {
expect(analytics.isAutocaptureEnabled('connect')).toBe(true);
expect(analytics.isAutocaptureEnabled('disconnect')).toBe(true);
expect(analytics.isAutocaptureEnabled('signature')).toBe(true);
expect(analytics.isAutocaptureEnabled('transaction')).toBe(true);
expect(analytics.isAutocaptureEnabled('chain')).toBe(true);
});
it('should return false when autocapture is disabled globally', async () => {
const instance = await FormoAnalytics.init('key', { autocapture: false });
expect(instance.isAutocaptureEnabled('connect')).toBe(false);
expect(instance.isAutocaptureEnabled('transaction')).toBe(false);
});
it('should return false for specific disabled event types', async () => {
const instance = await FormoAnalytics.init('key', {
autocapture: {
connect: true,
disconnect: false,
signature: true,
transaction: false,
chain: true,
},
});
expect(instance.isAutocaptureEnabled('connect')).toBe(true);
expect(instance.isAutocaptureEnabled('disconnect')).toBe(false);
expect(instance.isAutocaptureEnabled('transaction')).toBe(false);
});
});
describe('reset()', () => {
it('should clear currentUserId', () => {
analytics.currentUserId = 'user-123';
analytics.reset();
expect(analytics.currentUserId).toBeUndefined();
});
it('should remove storage keys', () => {
analytics.reset();
expect(mockStorageInstance.remove).toHaveBeenCalled();
});
});
describe('flush()', () => {
it('should call eventQueue.flush()', async () => {
await analytics.flush();
expect(mockEventQueue.flush).toHaveBeenCalled();
});
});
describe('cleanup()', () => {
it('should call eventQueue.cleanup()', async () => {
await analytics.cleanup();
expect(mockEventQueue.cleanup).toHaveBeenCalled();
});
});
});