forked from Iterable/react-native-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIterable.test.ts
More file actions
1473 lines (1369 loc) · 56.9 KB
/
Iterable.test.ts
File metadata and controls
1473 lines (1369 loc) · 56.9 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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { NativeEventEmitter, Platform } from 'react-native';
import { MockLinking } from '../../__mocks__/MockLinking';
import { MockRNIterableAPI } from '../../__mocks__/MockRNIterableAPI';
// import from the same location that consumers import from
import {
Iterable,
IterableAction,
IterableActionContext,
IterableActionSource,
IterableAttributionInfo,
IterableAuthResponse,
IterableCommerceItem,
IterableConfig,
IterableDataRegion,
IterableEventName,
IterableInAppCloseSource,
IterableInAppDeleteSource,
IterableInAppLocation,
IterableInAppMessage,
IterableInAppShowResponse,
IterableInAppTrigger,
IterableInAppTriggerType,
IterableLogLevel,
} from '../..';
import { TestHelper } from '../../__tests__/TestHelper';
describe('Iterable', () => {
beforeEach(() => {
jest.clearAllMocks();
});
afterEach(() => {
// Clean up all event listeners to prevent Jest worker process hanging
const nativeEmitter = new NativeEventEmitter();
nativeEmitter.removeAllListeners(IterableEventName.handleUrlCalled);
nativeEmitter.removeAllListeners(IterableEventName.handleInAppCalled);
nativeEmitter.removeAllListeners(
IterableEventName.handleCustomActionCalled
);
nativeEmitter.removeAllListeners(IterableEventName.handleAuthCalled);
nativeEmitter.removeAllListeners(IterableEventName.handleAuthSuccessCalled);
nativeEmitter.removeAllListeners(IterableEventName.handleAuthFailureCalled);
nativeEmitter.removeAllListeners(
IterableEventName.handleEmbeddedMessageUpdateCalled
);
nativeEmitter.removeAllListeners(
IterableEventName.handleEmbeddedMessagingDisabledCalled
);
// Clear any pending timers
jest.clearAllTimers();
});
describe('setEmail', () => {
it('should set the email', async () => {
const result = 'user@example.com';
// GIVEN an email
const email = 'user@example.com';
// WHEN Iterable.setEmail is called with the given email
Iterable.setEmail(email);
// THEN Iterable.getEmail returns the given email
return await Iterable.getEmail().then((mail) => {
expect(mail).toBe(result);
});
});
});
describe('setUserId', () => {
it('should set the userId', async () => {
const result = 'user1';
// GIVEN an userId
const userId = 'user1';
// WHEN Iterable.setUserId is called with the given userId
Iterable.setUserId(userId);
// THEN Iterable.getUserId returns the given userId
return await Iterable.getUserId().then((id) => {
expect(id).toBe(result);
});
});
});
describe('logout', () => {
it('should call setEmail with null', () => {
// GIVEN no parameters
// WHEN Iterable.logout is called
const setEmailSpy = jest.spyOn(Iterable, 'setEmail');
Iterable.logout();
// THEN Iterable.setEmail is called with null
expect(setEmailSpy).toBeCalledWith(null);
setEmailSpy.mockRestore();
});
it('should call setUserId with null', () => {
// GIVEN no parameters
// WHEN Iterable.logout is called
const setUserIdSpy = jest.spyOn(Iterable, 'setUserId');
Iterable.logout();
// THEN Iterable.setUserId is called with null
expect(setUserIdSpy).toBeCalledWith(null);
setUserIdSpy.mockRestore();
});
it('should clear email and userId', async () => {
// GIVEN a user is logged in
// This is just for testing purposed.
// Usually you'd either call `setEmail` or `setUserId`, but not both.
Iterable.setEmail('user@example.com');
Iterable.setUserId('user123');
// WHEN Iterable.logout is called
Iterable.logout();
// THEN email and userId are set to null
const email = await Iterable.getEmail();
const userId = await Iterable.getUserId();
expect(email).toBeNull();
expect(userId).toBeNull();
});
it('should call setEmail and setUserId with null', () => {
// GIVEN no parameters
const setEmailSpy = jest.spyOn(Iterable, 'setEmail');
const setUserIdSpy = jest.spyOn(Iterable, 'setUserId');
// WHEN Iterable.logout is called
Iterable.logout();
// THEN both methods are called with null
expect(setEmailSpy).toBeCalledWith(null);
expect(setUserIdSpy).toBeCalledWith(null);
// Clean up
setEmailSpy.mockRestore();
setUserIdSpy.mockRestore();
});
});
describe('disableDeviceForCurrentUser', () => {
it('should disable the device for the current user', () => {
// GIVEN no parameters
// WHEN Iterable.disableDeviceForCurrentUser is called
Iterable.disableDeviceForCurrentUser();
// THEN corresponding method is called on RNITerableAPI
expect(MockRNIterableAPI.disableDeviceForCurrentUser).toBeCalled();
});
});
describe('registerForPush', () => {
it('should re-register the device for push notifications', () => {
// GIVEN no parameters
// WHEN Iterable.registerForPush is called
Iterable.registerForPush();
// THEN corresponding method is called on RNIterableAPI
expect(MockRNIterableAPI.registerForPush).toBeCalled();
});
});
describe('getLastPushPayload', () => {
it('should return the last push payload', async () => {
const result = { var1: 'val1', var2: true };
// GIVEN no parameters
// WHEN the lastPushPayload is set
MockRNIterableAPI.lastPushPayload = { var1: 'val1', var2: true };
// THEN the lastPushPayload is returned when getLastPushPayload is called
return await Iterable.getLastPushPayload().then((payload) => {
expect(payload).toEqual(result);
});
});
});
describe('trackPushOpenWithCampaignId', () => {
it('should track the push open with the campaign id', () => {
// GIVEN the following parameters
const campaignId = 123;
const templateId = 234;
const messageId = 'someMessageId';
const appAlreadyRunning = false;
const dataFields = { dataFieldKey: 'dataFieldValue' };
// WHEN Iterable.trackPushOpenWithCampaignId is called
Iterable.trackPushOpenWithCampaignId(
campaignId,
templateId,
messageId,
appAlreadyRunning,
dataFields
);
// THEN corresponding function is called on RNIterableAPI
expect(MockRNIterableAPI.trackPushOpenWithCampaignId).toBeCalledWith(
campaignId,
templateId,
messageId,
appAlreadyRunning,
dataFields
);
});
});
describe('updateCart', () => {
it('should call IterableAPI.updateCart with the correct items', () => {
// GIVEN list of items
const items = [new IterableCommerceItem('id1', 'Boba Tea', 18, 26)];
// WHEN Iterable.updateCart is called
Iterable.updateCart(items);
// THEN corresponding function is called on RNIterableAPI
expect(MockRNIterableAPI.updateCart).toBeCalledWith(items);
});
});
describe('trackPurchase', () => {
it('should track the purchase', () => {
// GIVEN the following parameters
const total = 10;
const items = [new IterableCommerceItem('id1', 'Boba Tea', 18, 26)];
const dataFields = { dataFieldKey: 'dataFieldValue' };
// WHEN Iterable.trackPurchase is called
Iterable.trackPurchase(total, items, dataFields);
// THEN corresponding function is called on RNIterableAPI
expect(MockRNIterableAPI.trackPurchase).toBeCalledWith(
total,
items,
dataFields
);
});
it('should track the purchase when called with optional fields', () => {
// GIVEN the following parameters
const total = 5;
const items = [
new IterableCommerceItem(
'id',
'swordfish',
64,
1,
'SKU',
'description',
'url',
'imageUrl',
['sword', 'shield']
),
];
const dataFields = { key: 'value' };
// WHEN Iterable.trackPurchase is called
Iterable.trackPurchase(total, items, dataFields);
// THEN corresponding function is called on RNIterableAPI
expect(MockRNIterableAPI.trackPurchase).toBeCalledWith(
total,
items,
dataFields
);
});
});
describe('trackEvent', () => {
it('should call IterableAPI.trackEvent with the correct name and dataFields', () => {
// GIVEN the following parameters
const name = 'EventName';
const dataFields = { DatafieldKey: 'DatafieldValue' };
// WHEN Iterable.trackEvent is called
Iterable.trackEvent(name, dataFields);
// THEN corresponding function is called on RNIterableAPI
expect(MockRNIterableAPI.trackEvent).toBeCalledWith(name, dataFields);
});
});
describe('setAttributionInfo', () => {
it('should set the attribution info', async () => {
// GIVEN attribution info
const campaignId = 1234;
const templateId = 5678;
const messageId = 'qwer';
// WHEN Iterable.setAttributionInfo is called with the given attribution info
Iterable.setAttributionInfo(
new IterableAttributionInfo(campaignId, templateId, messageId)
);
// THEN Iterable.getAttrbutionInfo returns the given attribution info
return await Iterable.getAttributionInfo().then((attributionInfo) => {
expect(attributionInfo?.campaignId).toBe(campaignId);
expect(attributionInfo?.templateId).toBe(templateId);
expect(attributionInfo?.messageId).toBe(messageId);
});
});
});
describe('updateUser', () => {
it('should update the user', () => {
// GIVEN the following parameters
const dataFields = { field: 'value1' };
// WHEN Iterable.updateUser is called
Iterable.updateUser(dataFields, false);
// THEN corresponding function is called on RNIterableAPI
expect(MockRNIterableAPI.updateUser).toBeCalledWith(dataFields, false);
});
});
describe('updateEmail', () => {
it('should call IterableAPI.updateEmail with the correct email', () => {
// GIVEN the new email
const newEmail = 'woo@newemail.com';
// WHEN Iterable.updateEmail is called
Iterable.updateEmail(newEmail);
// THEN corresponding function is called on RNIterableAPI
expect(MockRNIterableAPI.updateEmail).toBeCalledWith(newEmail, undefined);
});
it('should call IterableAPI.updateEmail with the correct email and token', () => {
// GIVEN the new email and a token
const newEmail = 'woo@newemail.com';
const newToken = 'token2';
// WHEN Iterable.updateEmail is called
Iterable.updateEmail(newEmail, newToken);
// THEN corresponding function is called on RNITerableAPI
expect(MockRNIterableAPI.updateEmail).toBeCalledWith(newEmail, newToken);
});
});
describe('iterableConfig', () => {
it('should have default values', () => {
// GIVEN no parameters
// WHEN config is initialized
const config = new IterableConfig();
// THEN config has default values
expect(config.allowedProtocols).toEqual([]);
expect(config.androidSdkUseInMemoryStorageForInApps).toBe(false);
expect(config.authHandler).toBe(undefined);
expect(config.autoPushRegistration).toBe(true);
expect(config.checkForDeferredDeeplink).toBe(false);
expect(config.customActionHandler).toBe(undefined);
expect(config.dataRegion).toBe(IterableDataRegion.US);
expect(config.enableEmbeddedMessaging).toBe(false);
expect(config.encryptionEnforced).toBe(false);
expect(config.expiringAuthTokenRefreshPeriod).toBe(60.0);
expect(config.inAppDisplayInterval).toBe(30.0);
expect(config.inAppHandler).toBe(undefined);
expect(config.logLevel).toBe(IterableLogLevel.debug);
expect(config.logReactNativeSdkCalls).toBe(true);
expect(config.pushIntegrationName).toBe(undefined);
expect(config.urlHandler).toBe(undefined);
expect(config.useInMemoryStorageForInApps).toBe(false);
const configDict = config.toDict();
expect(configDict.allowedProtocols).toEqual([]);
expect(configDict.androidSdkUseInMemoryStorageForInApps).toBe(false);
expect(configDict.authHandlerPresent).toBe(false);
expect(configDict.autoPushRegistration).toBe(true);
expect(configDict.customActionHandlerPresent).toBe(false);
expect(configDict.dataRegion).toBe(IterableDataRegion.US);
expect(configDict.enableEmbeddedMessaging).toBe(false);
expect(configDict.encryptionEnforced).toBe(false);
expect(configDict.expiringAuthTokenRefreshPeriod).toBe(60.0);
expect(configDict.inAppDisplayInterval).toBe(30.0);
expect(configDict.inAppHandlerPresent).toBe(false);
expect(configDict.logLevel).toBe(IterableLogLevel.debug);
expect(configDict.pushIntegrationName).toBe(undefined);
expect(configDict.urlHandlerPresent).toBe(false);
expect(configDict.useInMemoryStorageForInApps).toBe(false);
});
});
describe('urlHandler', () => {
it('should open the url when canOpenURL returns true and urlHandler returns false', async () => {
// sets up event emitter
const nativeEmitter = new NativeEventEmitter();
nativeEmitter.removeAllListeners(IterableEventName.handleUrlCalled);
// sets up config file and urlHandler function
// urlHandler set to return false
const config = new IterableConfig();
config.logReactNativeSdkCalls = false;
config.urlHandler = jest.fn((_url: string, _: IterableActionContext) => {
return false;
});
// initialize Iterable object
Iterable.initialize('apiKey', config);
// GIVEN canOpenUrl set to return a promise that resolves to true
MockLinking.canOpenURL = jest.fn(async () => {
return await new Promise((resolve) => {
resolve(true);
});
});
MockLinking.openURL.mockReset();
const expectedUrl = 'https://somewhere.com';
const actionDict = { type: 'openUrl' };
const dict = {
url: expectedUrl,
context: { action: actionDict, source: 'inApp' },
};
// WHEN handleUrlCalled event is emitted
nativeEmitter.emit(IterableEventName.handleUrlCalled, dict);
// THEN urlHandler and MockLinking is called with expected url
return await TestHelper.delayed(0, () => {
expect(config.urlHandler).toBeCalledWith(expectedUrl, dict.context);
expect(MockLinking.openURL).toBeCalledWith(expectedUrl);
});
});
it('should not open the url when canOpenURL returns false and urlHandler returns false', async () => {
// sets up event emitter
const nativeEmitter = new NativeEventEmitter();
nativeEmitter.removeAllListeners(IterableEventName.handleUrlCalled);
// sets up config file and urlHandler function
// urlHandler set to return false
const config = new IterableConfig();
config.logReactNativeSdkCalls = false;
config.urlHandler = jest.fn((_url: string, _: IterableActionContext) => {
return false;
});
// initialize Iterable object
Iterable.initialize('apiKey', config);
// GIVEN canOpenUrl set to return a promise that resolves to false
MockLinking.canOpenURL = jest.fn(async () => {
return await new Promise((resolve) => {
resolve(false);
});
});
MockLinking.openURL.mockReset();
const expectedUrl = 'https://somewhere.com';
const actionDict = { type: 'openUrl' };
const dict = {
url: expectedUrl,
context: { action: actionDict, source: 'inApp' },
};
// WHEN handleUrlCalled event is emitted
nativeEmitter.emit(IterableEventName.handleUrlCalled, dict);
// THEN urlHandler is called and MockLinking.openURL is not called
return await TestHelper.delayed(0, () => {
expect(config.urlHandler).toBeCalledWith(expectedUrl, dict.context);
expect(MockLinking.openURL).not.toBeCalled();
});
});
it('should not open the url when canOpenURL returns true and urlHandler returns true', async () => {
// sets up event emitter
const nativeEmitter = new NativeEventEmitter();
nativeEmitter.removeAllListeners(IterableEventName.handleUrlCalled);
// sets up config file and urlHandler function
// urlHandler set to return true
const config = new IterableConfig();
config.logReactNativeSdkCalls = false;
config.urlHandler = jest.fn((_url: string, _: IterableActionContext) => {
return true;
});
// initialize Iterable object
Iterable.initialize('apiKey', config);
// GIVEN canOpenUrl set to return a promise that resolves to true
MockLinking.canOpenURL = jest.fn(async () => {
return await new Promise((resolve) => {
resolve(true);
});
});
MockLinking.openURL.mockReset();
const expectedUrl = 'https://somewhere.com';
const actionDict = { type: 'openUrl' };
const dict = {
url: expectedUrl,
context: { action: actionDict, source: 'inApp' },
};
// WHEN handleUrlCalled event is emitted
nativeEmitter.emit(IterableEventName.handleUrlCalled, dict);
// THEN urlHandler is called and MockLinking.openURL is not called
return await TestHelper.delayed(0, () => {
expect(config.urlHandler).toBeCalledWith(expectedUrl, dict.context);
expect(MockLinking.openURL).not.toBeCalled();
});
});
});
describe('customActionHandler', () => {
it('should be called with the correct action and context', () => {
// sets up event emitter
const nativeEmitter = new NativeEventEmitter();
nativeEmitter.removeAllListeners(
IterableEventName.handleCustomActionCalled
);
// sets up config file and customActionHandler function
// customActionHandler set to return true
const config = new IterableConfig();
config.logReactNativeSdkCalls = false;
config.customActionHandler = jest.fn(
(_action: IterableAction, _context: IterableActionContext) => {
return true;
}
);
// initialize Iterable object
Iterable.initialize('apiKey', config);
// GIVEN custom action name and custom action data
const actionName = 'zeeActionName';
const actionData = 'zeeActionData';
const actionDict = { type: actionName, data: actionData };
const actionSource = IterableActionSource.inApp;
const dict = {
action: actionDict,
context: { action: actionDict, source: IterableActionSource.inApp },
};
// WHEN handleCustomActionCalled event is emitted
nativeEmitter.emit(IterableEventName.handleCustomActionCalled, dict);
// THEN customActionHandler is called with expected action and expected context
const expectedAction = new IterableAction(actionName, actionData);
const expectedContext = new IterableActionContext(
expectedAction,
actionSource
);
expect(config.customActionHandler).toBeCalledWith(
expectedAction,
expectedContext
);
});
});
describe('handleAppLink', () => {
it('should call IterableAPI.handleAppLink', () => {
// GIVEN a link
const link = 'https://somewhere.com/link/something';
// WHEN Iterable.handleAppLink is called
Iterable.handleAppLink(link);
// THEN corresponding function is called on RNITerableAPI
expect(MockRNIterableAPI.handleAppLink).toBeCalledWith(link);
});
});
describe('updateSubscriptions', () => {
it('should call IterableAPI.updateSubscriptions with the correct parameters', () => {
// GIVEN the following parameters
const emailListIds = [1, 2, 3];
const unsubscribedChannelIds = [4, 5, 6];
const unsubscribedMessageTypeIds = [7, 8];
const subscribedMessageTypeIds = [9];
const campaignId = 10;
const templateId = 11;
// WHEN Iterable.updateSubscriptions is called
Iterable.updateSubscriptions(
emailListIds,
unsubscribedChannelIds,
unsubscribedMessageTypeIds,
subscribedMessageTypeIds,
campaignId,
templateId
);
// THEN corresponding function is called on RNIterableAPI
expect(MockRNIterableAPI.updateSubscriptions).toBeCalledWith(
emailListIds,
unsubscribedChannelIds,
unsubscribedMessageTypeIds,
subscribedMessageTypeIds,
campaignId,
templateId
);
});
});
describe('initialize', () => {
it('should call IterableAPI.initializeWithApiKey and save the config', async () => {
// GIVEN an API key and config
const apiKey = 'test-api-key';
const config = new IterableConfig();
config.logReactNativeSdkCalls = false;
config.logLevel = IterableLogLevel.debug;
// WHEN Iterable.initialize is called
const result = await Iterable.initialize(apiKey, config);
// THEN corresponding function is called on RNIterableAPI and config is saved
expect(MockRNIterableAPI.initializeWithApiKey).toBeCalledWith(
apiKey,
config.toDict(),
expect.any(String)
);
expect(Iterable.savedConfig).toBe(config);
expect(result).toBe(true);
});
it('should give the default config if no config is provided', async () => {
// GIVEN an API key
const apiKey = 'test-api-key';
// WHEN Iterable.initialize is called
const result = await Iterable.initialize(apiKey);
// THEN corresponding function is called on RNIterableAPI and config is saved
expect(Iterable.savedConfig).toStrictEqual(new IterableConfig());
expect(result).toBe(true);
});
});
describe('initialize2', () => {
it('should call IterableAPI.initialize2WithApiKey with an endpoint and save the config', async () => {
// GIVEN an API key, config, and endpoint
const apiKey = 'test-api-key';
const config = new IterableConfig();
config.logReactNativeSdkCalls = false;
const apiEndPoint = 'https://api.staging.iterable.com';
// WHEN Iterable.initialize2 is called
const result = await Iterable.initialize2(apiKey, config, apiEndPoint);
// THEN corresponding function is called on RNIterableAPI and config is saved
expect(MockRNIterableAPI.initialize2WithApiKey).toBeCalledWith(
apiKey,
config.toDict(),
expect.any(String),
apiEndPoint
);
expect(Iterable.savedConfig).toBe(config);
expect(result).toBe(true);
});
it('should give the default config if no config is provided', async () => {
// GIVEN an API key
const apiKey = 'test-api-key';
const apiEndPoint = 'https://api.staging.iterable.com';
// WHEN Iterable.initialize is called
const result = await Iterable.initialize2(apiKey, undefined, apiEndPoint);
// THEN corresponding function is called on RNIterableAPI and config is saved
expect(Iterable.savedConfig).toStrictEqual(new IterableConfig());
expect(result).toBe(true);
});
});
describe('wakeApp', () => {
it('should call IterableAPI.wakeApp on Android', () => {
// GIVEN Android platform
const originalPlatform = Platform.OS;
Object.defineProperty(Platform, 'OS', {
value: 'android',
writable: true,
});
// WHEN Iterable.wakeApp is called
Iterable.wakeApp();
// THEN corresponding function is called on RNIterableAPI
expect(MockRNIterableAPI.wakeApp).toBeCalled();
// Restore original platform
Object.defineProperty(Platform, 'OS', {
value: originalPlatform,
writable: true,
});
});
it('should not call IterableAPI.wakeApp on iOS', () => {
// GIVEN iOS platform
const originalPlatform = Platform.OS;
Object.defineProperty(Platform, 'OS', {
value: 'ios',
writable: true,
});
// WHEN Iterable.wakeApp is called
Iterable.wakeApp();
// THEN corresponding function is not called on RNIterableAPI
expect(MockRNIterableAPI.wakeApp).not.toBeCalled();
// Restore original platform
Object.defineProperty(Platform, 'OS', {
value: originalPlatform,
writable: true,
});
});
});
describe('trackInAppOpen', () => {
it('should call IterableAPI.trackInAppOpen with the correct parameters', () => {
// GIVEN an in-app message and location
const message = new IterableInAppMessage(
'1234',
4567,
new IterableInAppTrigger(IterableInAppTriggerType.immediate),
new Date(),
new Date(),
false,
undefined,
undefined,
false,
0
);
const location = IterableInAppLocation.inApp;
// WHEN Iterable.trackInAppOpen is called
Iterable.trackInAppOpen(message, location);
// THEN corresponding function is called on RNIterableAPI
expect(MockRNIterableAPI.trackInAppOpen).toBeCalledWith(
message.messageId,
location
);
});
});
describe('trackInAppClick', () => {
it('should call IterableAPI.trackInAppClick with the correct parameters', () => {
// GIVEN an in-app message, location, and clicked URL
const message = new IterableInAppMessage(
'1234',
4567,
new IterableInAppTrigger(IterableInAppTriggerType.immediate),
new Date(),
new Date(),
false,
undefined,
undefined,
false,
0
);
const location = IterableInAppLocation.inApp;
const clickedUrl = 'https://www.example.com';
// WHEN Iterable.trackInAppClick is called
Iterable.trackInAppClick(message, location, clickedUrl);
// THEN corresponding function is called on RNIterableAPI
expect(MockRNIterableAPI.trackInAppClick).toBeCalledWith(
message.messageId,
location,
clickedUrl
);
});
});
describe('trackInAppClose', () => {
it('should call IterableAPI.trackInAppClose with the correct parameters', () => {
// GIVEN an in-app message, location, and source (no URL)
const message = new IterableInAppMessage(
'1234',
4567,
new IterableInAppTrigger(IterableInAppTriggerType.immediate),
new Date(),
new Date(),
false,
undefined,
undefined,
false,
0
);
const location = IterableInAppLocation.inApp;
const source = IterableInAppCloseSource.back;
// WHEN Iterable.trackInAppClose is called
Iterable.trackInAppClose(message, location, source);
// THEN corresponding function is called on RNIterableAPI
expect(MockRNIterableAPI.trackInAppClose).toBeCalledWith(
message.messageId,
location,
source,
undefined
);
});
it('should call IterableAPI.trackInAppClose with a clicked URL when provided', () => {
// GIVEN an in-app message, location, source, and clicked URL
const message = new IterableInAppMessage(
'1234',
4567,
new IterableInAppTrigger(IterableInAppTriggerType.immediate),
new Date(),
new Date(),
false,
undefined,
undefined,
false,
0
);
const location = IterableInAppLocation.inApp;
const source = IterableInAppCloseSource.back;
const clickedUrl = 'https://www.example.com';
// WHEN Iterable.trackInAppClose is called
Iterable.trackInAppClose(message, location, source, clickedUrl);
// THEN corresponding function is called on RNIterableAPI
expect(MockRNIterableAPI.trackInAppClose).toBeCalledWith(
message.messageId,
location,
source,
clickedUrl
);
});
});
describe('inAppConsume', () => {
it('should call IterableAPI.inAppConsume with the correct parameters', () => {
// GIVEN an in-app message, location, and delete source
const message = new IterableInAppMessage(
'1234',
4567,
new IterableInAppTrigger(IterableInAppTriggerType.immediate),
new Date(),
new Date(),
false,
undefined,
undefined,
false,
0
);
const location = IterableInAppLocation.inApp;
const source = IterableInAppDeleteSource.deleteButton;
// WHEN Iterable.inAppConsume is called
Iterable.inAppConsume(message, location, source);
// THEN corresponding function is called on RNIterableAPI
expect(MockRNIterableAPI.inAppConsume).toBeCalledWith(
message.messageId,
location,
source
);
});
});
describe('getVersionFromPackageJson', () => {
it('should return the version from the package.json file', () => {
// GIVEN no parameters
// WHEN Iterable.getVersionFromPackageJson is called
const version = Iterable.getVersionFromPackageJson();
// THEN a version string is returned
expect(typeof version).toBe('string');
expect(version.length).toBeGreaterThan(0);
});
});
describe('setupEventHandlers', () => {
it('should call inAppHandler when handleInAppCalled event is emitted', () => {
// sets up event emitter
const nativeEmitter = new NativeEventEmitter();
nativeEmitter.removeAllListeners(IterableEventName.handleInAppCalled);
// sets up config file and inAppHandler function
const config = new IterableConfig();
config.logReactNativeSdkCalls = false;
config.inAppHandler = jest.fn((_message: IterableInAppMessage) => {
return IterableInAppShowResponse.show;
});
// initialize Iterable object
Iterable.initialize('apiKey', config);
// GIVEN message dictionary
const messageDict = {
messageId: '1234',
campaignId: 4567,
trigger: { type: 0 },
createdAt: new Date().toISOString(),
expiresAt: new Date().toISOString(),
saveToInbox: false,
inboxMetadata: undefined,
customPayload: undefined,
read: false,
priorityLevel: 0,
};
// WHEN handleInAppCalled event is emitted
nativeEmitter.emit(IterableEventName.handleInAppCalled, messageDict);
// THEN inAppHandler is called and setInAppShowResponse is called
expect(config.inAppHandler).toBeCalledWith(
expect.any(IterableInAppMessage)
);
expect(MockRNIterableAPI.setInAppShowResponse).toBeCalledWith(
IterableInAppShowResponse.show
);
});
describe('authHandler', () => {
it('should call authHandler when handleAuthCalled event is emitted', async () => {
// sets up event emitter
const nativeEmitter = new NativeEventEmitter();
nativeEmitter.removeAllListeners(IterableEventName.handleAuthCalled);
nativeEmitter.removeAllListeners(
IterableEventName.handleAuthSuccessCalled
);
nativeEmitter.removeAllListeners(
IterableEventName.handleAuthFailureCalled
);
// sets up config file and authHandler function
const config = new IterableConfig();
config.logReactNativeSdkCalls = false;
const successCallback = jest.fn();
const failureCallback = jest.fn();
const authResponse = new IterableAuthResponse();
authResponse.authToken = 'test-token';
authResponse.successCallback = successCallback;
authResponse.failureCallback = failureCallback;
config.authHandler = jest.fn(() => {
return Promise.resolve(authResponse);
});
// initialize Iterable object
Iterable.initialize('apiKey', config);
// GIVEN auth handler returns AuthResponse
// WHEN handleAuthCalled event is emitted
nativeEmitter.emit(IterableEventName.handleAuthCalled);
// WHEN handleAuthSuccessCalled event is emitted
nativeEmitter.emit(IterableEventName.handleAuthSuccessCalled);
// THEN passAlongAuthToken is called with the token and success callback is called after timeout
return await TestHelper.delayed(1100, () => {
expect(MockRNIterableAPI.passAlongAuthToken).toBeCalledWith(
'test-token'
);
expect(successCallback).toBeCalled();
expect(failureCallback).not.toBeCalled();
});
});
it('should call authHandler when handleAuthFailureCalled event is emitted', async () => {
// sets up event emitter
const nativeEmitter = new NativeEventEmitter();
nativeEmitter.removeAllListeners(IterableEventName.handleAuthCalled);
nativeEmitter.removeAllListeners(
IterableEventName.handleAuthSuccessCalled
);
nativeEmitter.removeAllListeners(
IterableEventName.handleAuthFailureCalled
);
// sets up config file and authHandler function
const config = new IterableConfig();
config.logReactNativeSdkCalls = false;
const successCallback = jest.fn();
const failureCallback = jest.fn();
const authResponse = new IterableAuthResponse();
authResponse.authToken = 'test-token';
authResponse.successCallback = successCallback;
authResponse.failureCallback = failureCallback;
config.authHandler = jest.fn(() => {
// Why are we resolving when this is a failure?
return Promise.resolve(authResponse);
});
// initialize Iterable object
Iterable.initialize('apiKey', config);
// GIVEN auth handler returns AuthResponse
// WHEN handleAuthCalled event is emitted
nativeEmitter.emit(IterableEventName.handleAuthCalled);
// WHEN handleAuthFailureCalled event is emitted
nativeEmitter.emit(IterableEventName.handleAuthFailureCalled);
// THEN passAlongAuthToken is called with the token and failure callback is called after timeout
return await TestHelper.delayed(1100, () => {
expect(MockRNIterableAPI.passAlongAuthToken).toBeCalledWith(
'test-token'
);
expect(failureCallback).toBeCalled();
expect(successCallback).not.toBeCalled();
});
});
it('should call authHandler when handleAuthCalled event is emitted and returns a string token', async () => {
// sets up event emitter
const nativeEmitter = new NativeEventEmitter();
nativeEmitter.removeAllListeners(IterableEventName.handleAuthCalled);
// sets up config file and authHandler function
const config = new IterableConfig();
config.logReactNativeSdkCalls = false;
config.authHandler = jest.fn(() => {
return Promise.resolve('string-token');
});
// initialize Iterable object
Iterable.initialize('apiKey', config);
// GIVEN auth handler returns string token
// WHEN handleAuthCalled event is emitted
nativeEmitter.emit(IterableEventName.handleAuthCalled);
// THEN passAlongAuthToken is called with the string token
return await TestHelper.delayed(100, () => {
expect(MockRNIterableAPI.passAlongAuthToken).toBeCalledWith(
'string-token'
);
});
});
it('should call authHandler when handleAuthCalled event is emitted and returns an unexpected response', () => {
// sets up event emitter
const nativeEmitter = new NativeEventEmitter();
nativeEmitter.removeAllListeners(IterableEventName.handleAuthCalled);
// sets up config file and authHandler function
const config = new IterableConfig();
config.logReactNativeSdkCalls = false;
config.authHandler = jest.fn(() => {
return Promise.resolve({ unexpected: 'object' } as unknown as
| string
| IterableAuthResponse);
});
// initialize Iterable object
Iterable.initialize('apiKey', config);
// GIVEN auth handler returns unexpected response
// WHEN handleAuthCalled event is emitted
nativeEmitter.emit(IterableEventName.handleAuthCalled);
// THEN error is logged (we can't easily test console.log, but we can verify no crash)
expect(MockRNIterableAPI.passAlongAuthToken).not.toBeCalled();
});
it('should call authHandler when handleAuthCalled event is emitted and rejects the promise', () => {
// sets up event emitter
const nativeEmitter = new NativeEventEmitter();
nativeEmitter.removeAllListeners(IterableEventName.handleAuthCalled);
// sets up config file and authHandler function
const config = new IterableConfig();
config.logReactNativeSdkCalls = false;
config.authHandler = jest.fn(() => {
return Promise.reject(new Error('Auth failed'));
});
// initialize Iterable object
Iterable.initialize('apiKey', config);
// GIVEN auth handler rejects promise
// WHEN handleAuthCalled event is emitted
nativeEmitter.emit(IterableEventName.handleAuthCalled);
// THEN error is logged (we can't easily test console.log, but we can verify no crash)
expect(MockRNIterableAPI.passAlongAuthToken).not.toBeCalled();
});
});
});
describe('authManager', () => {
describe('pauseAuthRetries', () => {
it('should call RNIterableAPI.pauseAuthRetries with true when pauseRetry is true', () => {
// GIVEN pauseRetry is true
const pauseRetry = true;
// WHEN pauseAuthRetries is called
Iterable.authManager.pauseAuthRetries(pauseRetry);
// THEN RNIterableAPI.pauseAuthRetries is called with true
expect(MockRNIterableAPI.pauseAuthRetries).toBeCalledWith(true);
});
it('should call RNIterableAPI.pauseAuthRetries with false when pauseRetry is false', () => {
// GIVEN pauseRetry is false
const pauseRetry = false;
// WHEN pauseAuthRetries is called
Iterable.authManager.pauseAuthRetries(pauseRetry);
// THEN RNIterableAPI.pauseAuthRetries is called with false
expect(MockRNIterableAPI.pauseAuthRetries).toBeCalledWith(false);
});