-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
NewNotifications.js
1443 lines (1336 loc) · 50.9 KB
/
NewNotifications.js
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
'use strict';
import { Platform } from '@unimodules/core';
import Constants from 'expo-constants';
import * as Device from 'expo-device';
import * as FileSystem from 'expo-file-system';
import * as Notifications from 'expo-notifications';
import { Alert, AppState } from 'react-native';
import * as TestUtils from '../TestUtils';
import { isInteractive } from '../utils/Environment';
import { waitFor } from './helpers';
export const name = 'expo-notifications';
export async function test(t) {
const shouldSkipTestsRequiringPermissions = await TestUtils.shouldSkipTestsRequiringPermissionsAsync();
const describeWithPermissions = shouldSkipTestsRequiringPermissions ? t.xdescribe : t.describe;
t.describe('expo-notifications', () => {
t.describe('getDevicePushTokenAsync', () => {
let subscription = null;
let tokenFromEvent = null;
let tokenFromMethodCall = null;
t.beforeAll(() => {
subscription = Notifications.addPushTokenListener(newEvent => {
tokenFromEvent = newEvent;
});
});
t.afterAll(() => {
if (subscription) {
subscription.remove();
subscription = null;
}
});
if (Platform.OS === 'android' || Platform.OS === 'ios') {
t.it('resolves with a string', async () => {
const devicePushToken = await Notifications.getDevicePushTokenAsync();
t.expect(typeof devicePushToken.data).toBe('string');
tokenFromMethodCall = devicePushToken;
});
}
if (Platform.OS === 'web') {
t.it('resolves with an object', async () => {
const devicePushToken = await Notifications.getDevicePushTokenAsync();
t.expect(typeof devicePushToken.data).toBe('object');
tokenFromMethodCall = devicePushToken;
});
}
t.it('emits an event with token (or not, if getDevicePushTokenAsync failed)', async () => {
// It would be better to do `if (!tokenFromMethodCall) { pending(); } else { ... }`
// but `t.pending()` still doesn't work.
await waitFor(500);
t.expect(tokenFromEvent).toEqual(tokenFromMethodCall);
});
t.it('resolves when multiple calls are issued', async () => {
const results = await Promise.all([
Notifications.getDevicePushTokenAsync(),
Notifications.getDevicePushTokenAsync(),
]);
t.expect(results[0].data).toBeDefined();
t.expect(results[0].data).toBe(results[1].data);
});
// Not running this test on web since Expo push notification doesn't yet support web.
const itWithExpoPushToken = ['ios', 'android'].includes(Platform.OS) ? t.it : t.xit;
itWithExpoPushToken('fetches Expo push token', async () => {
let experienceId = undefined;
if (!Constants.manifest) {
// Absence of manifest means we're running out of managed workflow
// in bare-expo. @exponent/bare-expo "experience" has been configured
// to use Apple Push Notification key that will work in bare-expo.
experienceId = '@exponent/bare-expo';
}
const expoPushToken = await Notifications.getExpoPushTokenAsync({
experienceId,
});
t.expect(expoPushToken.type).toBe('expo');
t.expect(typeof expoPushToken.data).toBe('string');
});
itWithExpoPushToken('resolves when mixed multiple calls are issued', async () => {
let experienceId = undefined;
if (!Constants.manifest) {
// Absence of manifest means we're running out of managed workflow
// in bare-expo. @exponent/bare-expo "experience" has been configured
// to use Apple Push Notification key that will work in bare-expo.
experienceId = '@exponent/bare-expo';
}
await Promise.all([
Notifications.getExpoPushTokenAsync({ experienceId }),
Notifications.getDevicePushTokenAsync(),
]);
});
});
// Not running those tests on web since Expo push notification doesn't yet support web.
const describeWithExpoPushToken = ['ios', 'android'].includes(Platform.OS)
? t.describe
: t.xdescribe;
describeWithExpoPushToken('when a push notification is sent', () => {
let notificationToHandle;
let handleSuccessEvent;
let handleErrorEvent;
let receivedEvent = null;
let receivedSubscription = null;
let expoPushToken;
let handleFuncOverride;
t.beforeAll(async () => {
let experienceId = undefined;
if (!Constants.manifest) {
// Absence of manifest means we're running out of managed workflow
// in bare-expo. @exponent/bare-expo "experience" has been configured
// to use Apple Push Notification key that will work in bare-expo.
experienceId = '@exponent/bare-expo';
}
const pushToken = await Notifications.getExpoPushTokenAsync({
experienceId,
});
expoPushToken = pushToken.data;
Notifications.setNotificationHandler({
handleNotification: async notification => {
notificationToHandle = notification;
if (handleFuncOverride) {
return await handleFuncOverride(notification);
} else {
return {
shouldPlaySound: false,
shouldSetBadge: false,
shouldShowAlert: true,
};
}
},
handleSuccess: event => {
handleSuccessEvent = event;
},
handleError: (...event) => {
handleErrorEvent = event;
},
});
receivedSubscription = Notifications.addNotificationReceivedListener(event => {
receivedEvent = event;
});
});
t.beforeEach(async () => {
receivedEvent = null;
handleErrorEvent = null;
handleSuccessEvent = null;
notificationToHandle = null;
await sendTestPushNotification(expoPushToken);
});
t.afterAll(() => {
if (receivedSubscription) {
receivedSubscription.remove();
receivedSubscription = null;
}
Notifications.setNotificationHandler(null);
});
t.it('calls the `handleNotification` callback of the notification handler', async () => {
let iterations = 0;
while (iterations < 5) {
iterations += 1;
if (notificationToHandle) {
break;
}
await waitFor(1000);
}
t.expect(notificationToHandle).not.toBeNull();
});
t.it('emits a “notification received” event', async () => {
let iterations = 0;
while (iterations < 5) {
iterations += 1;
if (receivedEvent) {
break;
}
await waitFor(1000);
}
t.expect(receivedEvent).not.toBeNull();
});
t.describe('if handler responds in time', async () => {
t.it(
'calls `handleSuccess` callback of the notification handler',
async () => {
let iterations = 0;
while (iterations < 5) {
iterations += 1;
if (handleSuccessEvent) {
break;
}
await waitFor(1000);
}
t.expect(handleSuccessEvent).not.toBeNull();
t.expect(handleErrorEvent).toBeNull();
},
10000
);
});
t.describe('if handler fails to respond in time', async () => {
t.beforeAll(() => {
handleFuncOverride = async () => {
await waitFor(3000);
return {
shouldPlaySound: false,
shouldSetBadge: false,
shouldShowAlert: true,
};
};
});
t.afterAll(() => {
handleFuncOverride = null;
});
t.it(
'calls `handleError` callback of the notification handler',
async () => {
let iterations = 0;
while (iterations < 5) {
iterations += 1;
if (handleErrorEvent) {
break;
}
await waitFor(1000);
}
t.expect(handleErrorEvent).not.toBeNull();
t.expect(typeof handleErrorEvent[0]).toBe('string');
t.expect(handleSuccessEvent).toBeNull();
},
10000
);
});
});
t.describe('getPermissionsAsync', () => {
t.it('resolves with an object', async () => {
const permissions = await Notifications.getPermissionsAsync();
t.expect(permissions).toBeDefined();
t.expect(typeof permissions).toBe('object');
});
});
describeWithPermissions('requestPermissionsAsync', () => {
t.it('resolves without any arguments', async () => {
const permissions = await Notifications.requestPermissionsAsync();
t.expect(permissions).toBeDefined();
t.expect(typeof permissions).toBe('object');
});
t.it('resolves with specific permissions requested', async () => {
const permissions = await Notifications.requestPermissionsAsync({
providesAppNotificationSettings: true,
allowsAlert: true,
allowsBadge: true,
allowsSound: true,
});
t.expect(permissions).toBeDefined();
t.expect(typeof permissions).toBe('object');
});
});
t.describe('presentNotificationAsync', () => {
t.it('presents a simple notification', async () => {
await Notifications.presentNotificationAsync({
title: 'Sample title',
subtitle: 'What an event!',
body: 'An interesting event has just happened',
badge: 1,
});
});
t.it('presents a notification with attachments', async () => {
const fileUri = FileSystem.documentDirectory + 'expo-notifications-test-image.jpg';
await FileSystem.downloadAsync('http://placekitten.com/200/300', fileUri);
await Notifications.presentNotificationAsync({
title: 'Look at that kitten! ➡️',
body: 'What a cutie!',
attachments: [{ uri: fileUri }],
});
});
});
t.describe('Notification channels', () => {
// Implementation detail!
const fallbackChannelId = 'expo_notifications_fallback_notification_channel';
const fallbackChannelName = 'Miscellaneous';
const testChannelId = 'test-channel-id';
const testChannel = {
name: 'Test channel',
};
t.describe('getNotificationChannelAsync()', () => {
t.it('returns null if there is no such channel', async () => {
const channel = await Notifications.getNotificationChannelAsync(
'non-existent-channel-id'
);
t.expect(channel).toBe(null);
});
// Test push notifications sent without a channel ID should create a fallback channel
if (Platform.OS === 'android' && Device.platformApiLevel >= 26) {
t.it('returns an object if there is such channel', async () => {
const channel = await Notifications.getNotificationChannelAsync(fallbackChannelId);
t.expect(channel).toBeDefined();
});
}
});
t.describe('getNotificationChannelsAsync()', () => {
t.it('returns an array', async () => {
const channels = await Notifications.getNotificationChannelsAsync();
t.expect(channels).toEqual(t.jasmine.any(Array));
});
// Test push notifications sent without a channel ID should create a fallback channel
if (Platform.OS === 'android' && Device.platformApiLevel >= 26) {
t.it('contains the fallback channel', async () => {
const channels = await Notifications.getNotificationChannelsAsync();
t.expect(channels).toContain(
t.jasmine.objectContaining({
// Implementation detail!
id: fallbackChannelId,
name: fallbackChannelName,
})
);
});
}
});
t.describe('setNotificationChannelAsync()', () => {
t.afterEach(async () => {
await Notifications.deleteNotificationChannelAsync(testChannelId);
});
if (Platform.OS === 'android' && Device.platformApiLevel >= 26) {
t.it('returns the modified channel', async () => {
const channel = await Notifications.setNotificationChannelAsync(
testChannelId,
testChannel
);
t.expect(channel).toEqual(
t.jasmine.objectContaining({ ...testChannel, id: testChannelId })
);
});
t.it('creates a channel', async () => {
const preChannels = await Notifications.getNotificationChannelsAsync();
const channelSpec = t.jasmine.objectContaining({ ...testChannel, id: testChannelId });
t.expect(preChannels).not.toContain(channelSpec);
await Notifications.setNotificationChannelAsync(testChannelId, testChannel);
const postChannels = await Notifications.getNotificationChannelsAsync();
t.expect(postChannels).toContain(channelSpec);
t.expect(postChannels.length).toBeGreaterThan(preChannels.length);
});
t.it('sets custom properties', async () => {
const spec = {
name: 'Name',
importance: Notifications.AndroidImportance.MIN,
bypassDnd: true,
description: 'Test channel',
lightColor: '#FF231F7C',
lockscreenVisibility: Notifications.AndroidNotificationVisibility.SECRET,
showBadge: false,
sound: null,
audioAttributes: {
usage: Notifications.AndroidAudioUsage.NOTIFICATION_COMMUNICATION_INSTANT,
contentType: Notifications.AndroidAudioContentType.SONIFICATION,
flags: {
enforceAudibility: true,
requestHardwareAudioVideoSynchronization: true,
},
},
vibrationPattern: [500, 500],
enableLights: true,
enableVibrate: true,
};
const channel = await Notifications.setNotificationChannelAsync(testChannelId, spec);
t.expect(channel).toEqual(t.jasmine.objectContaining({ ...spec, id: testChannelId }));
});
t.it('assigns a channel to a group', async () => {
const groupId = 'test-group-id';
try {
await Notifications.setNotificationChannelGroupAsync(groupId, { name: 'Test group' });
const channel = await Notifications.setNotificationChannelAsync(testChannelId, {
...testChannel,
groupId,
});
t.expect(channel.groupId).toBe(groupId);
const group = await Notifications.getNotificationChannelGroupAsync(groupId);
t.expect(group.channels).toContain(t.jasmine.objectContaining(testChannel));
} catch (e) {
await Notifications.deleteNotificationChannelAsync(testChannelId);
await Notifications.deleteNotificationChannelGroupAsync(groupId);
throw e;
}
});
t.it('updates a channel', async () => {
await Notifications.setNotificationChannelAsync(testChannelId, {
name: 'Name before change',
});
await Notifications.setNotificationChannelAsync(testChannelId, {
name: 'Name after change',
});
const channels = await Notifications.getNotificationChannelsAsync();
t.expect(channels).toContain(
t.jasmine.objectContaining({
name: 'Name after change',
id: testChannelId,
})
);
t.expect(channels).not.toContain(
t.jasmine.objectContaining({
name: 'Name before change',
id: testChannelId,
})
);
});
} else {
t.it("doesn't throw an error", async () => {
await Notifications.setNotificationChannelAsync(testChannelId, testChannel);
});
}
});
t.describe('deleteNotificationChannelAsync()', () => {
if (Platform.OS === 'android' && Device.platformApiLevel >= 26) {
t.it('deletes a channel', async () => {
const preChannels = await Notifications.getNotificationChannelsAsync();
const channelSpec = t.jasmine.objectContaining({ ...testChannel, id: testChannelId });
t.expect(preChannels).not.toContain(channelSpec);
await Notifications.setNotificationChannelAsync(testChannelId, testChannel);
const postChannels = await Notifications.getNotificationChannelsAsync();
await Notifications.deleteNotificationChannelAsync(testChannelId);
t.expect(postChannels).toContain(channelSpec);
t.expect(postChannels.length).toBeGreaterThan(preChannels.length);
});
} else {
t.it("doesn't throw an error", async () => {
await Notifications.deleteNotificationChannelAsync(testChannelId, testChannel);
});
}
});
});
t.describe('Notification channel groups', () => {
const testChannelGroupId = 'test-channel-group-id';
const testChannelGroup = { name: 'Test channel group' };
t.describe('getNotificationChannelGroupAsync()', () => {
t.it('returns null if there is no such channel group', async () => {
const channelGroup = await Notifications.getNotificationChannelGroupAsync(
'non-existent-channel-group-id'
);
t.expect(channelGroup).toBe(null);
});
if (Platform.OS === 'android' && Device.platformApiLevel >= 26) {
t.it('returns an object if there is such channel group', async () => {
await Notifications.setNotificationChannelGroupAsync(
testChannelGroupId,
testChannelGroup
);
const channel = await Notifications.getNotificationChannelGroupAsync(
testChannelGroupId
);
await Notifications.deleteNotificationChannelGroupAsync(testChannelGroupId);
t.expect(channel).toBeDefined();
});
}
});
t.describe('getNotificationChannelGroupsAsync()', () => {
if (Platform.OS === 'android' && Device.platformApiLevel >= 28) {
t.it('returns an array', async () => {
const channels = await Notifications.getNotificationChannelGroupsAsync();
t.expect(channels).toEqual(t.jasmine.any(Array));
});
t.it('returns existing channel groups', async () => {
const channel = await Notifications.setNotificationChannelGroupAsync(
testChannelGroupId,
testChannelGroup
);
const channels = await Notifications.getNotificationChannelGroupsAsync();
await Notifications.deleteNotificationChannelGroupAsync(testChannelGroupId);
t.expect(channels).toContain(channel);
});
} else {
t.it("doesn't throw an error", async () => {
await Notifications.getNotificationChannelGroupsAsync();
});
}
});
t.describe('setNotificationChannelGroupsAsync()', () => {
t.afterEach(async () => {
await Notifications.deleteNotificationChannelGroupAsync(testChannelGroupId);
});
if (Platform.OS === 'android' && Device.platformApiLevel >= 26) {
t.it('returns the modified channel group', async () => {
const group = await Notifications.setNotificationChannelGroupAsync(
testChannelGroupId,
testChannelGroup
);
t.expect(group).toEqual(
t.jasmine.objectContaining({ ...testChannelGroup, id: testChannelGroupId })
);
});
t.it('creates a channel group', async () => {
const preChannelGroups = await Notifications.getNotificationChannelGroupsAsync();
const channelGroupSpec = t.jasmine.objectContaining({
...testChannelGroup,
id: testChannelGroupId,
});
t.expect(preChannelGroups).not.toContain(channelGroupSpec);
await Notifications.setNotificationChannelGroupAsync(
testChannelGroupId,
testChannelGroup
);
const postChannelGroups = await Notifications.getNotificationChannelGroupsAsync();
t.expect(postChannelGroups).toContain(channelGroupSpec);
t.expect(postChannelGroups.length).toBeGreaterThan(preChannelGroups.length);
});
t.it('sets custom properties', async () => {
const createSpec = {
name: 'Test channel group',
description: 'Used by `test-suite`',
};
const channelGroup = await Notifications.setNotificationChannelGroupAsync(
testChannelGroupId,
createSpec
);
const groupSpec = { ...createSpec, id: testChannelGroupId };
if (Device.platformApiLevel < 28) {
// Groups descriptions is only supported on API 28+
delete groupSpec.description;
}
t.expect(channelGroup).toEqual(
t.jasmine.objectContaining({ ...groupSpec, id: testChannelGroupId })
);
});
t.it('updates a channel group', async () => {
await Notifications.setNotificationChannelGroupAsync(testChannelGroupId, {
name: 'Name before change',
});
await Notifications.setNotificationChannelGroupAsync(testChannelGroupId, {
name: 'Name after change',
});
const channelGroups = await Notifications.getNotificationChannelGroupsAsync();
t.expect(channelGroups).toContain(
t.jasmine.objectContaining({
name: 'Name after change',
id: testChannelGroupId,
})
);
t.expect(channelGroups).not.toContain(
t.jasmine.objectContaining({
name: 'Name before change',
id: testChannelGroupId,
})
);
});
} else {
t.it("doesn't throw an error", async () => {
await Notifications.setNotificationChannelGroupAsync(
testChannelGroupId,
testChannelGroup
);
});
}
});
});
t.describe('getBadgeCountAsync', () => {
t.it('resolves with an integer', async () => {
const badgeCount = await Notifications.getBadgeCountAsync();
t.expect(typeof badgeCount).toBe('number');
});
});
t.describe('setBadgeCountAsync', () => {
t.it('resolves with a boolean', async () => {
const randomCounter = Math.ceil(Math.random() * 9) + 1;
const result = await Notifications.setBadgeCountAsync(randomCounter);
t.expect(typeof result).toBe('boolean');
});
t.it('sets a retrievable counter (if set succeeds)', async () => {
const randomCounter = Math.ceil(Math.random() * 9) + 1;
if (await Notifications.setBadgeCountAsync(randomCounter)) {
const badgeCount = await Notifications.getBadgeCountAsync();
t.expect(badgeCount).toBe(randomCounter);
} else {
// TODO: add t.pending() when it starts to work
}
});
t.it('clears the counter', async () => {
const clearingCounter = 0;
await Notifications.setBadgeCountAsync(clearingCounter);
const badgeCount = await Notifications.getBadgeCountAsync();
t.expect(badgeCount).toBe(clearingCounter);
});
});
t.describe('getPresentedNotificationsAsync()', () => {
const identifier = 'test-containing-id';
const notificationStatuses = {};
t.beforeAll(() => {
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
}),
handleSuccess: notificationId => {
notificationStatuses[notificationId] = true;
},
});
});
t.it('resolves with an array containing a displayed notification', async () => {
await Notifications.presentNotificationAsync(
{
title: 'Sample title',
subtitle: 'What an event!',
body: 'An interesting event has just happened',
badge: 1,
},
identifier
);
await waitFor(1000);
const displayedNotifications = await Notifications.getPresentedNotificationsAsync();
t.expect(displayedNotifications).toContain(
t.jasmine.objectContaining({
request: t.jasmine.objectContaining({
identifier,
}),
})
);
});
t.it('resolves with an array that does not contain a canceled notification', async () => {
await Notifications.dismissNotificationAsync(identifier);
await waitFor(1000);
const displayedNotifications = await Notifications.getPresentedNotificationsAsync();
t.expect(displayedNotifications).not.toContain(
t.jasmine.objectContaining({
request: t.jasmine.objectContaining({
identifier,
}),
})
);
});
if (Constants.appOwnership === 'expo') {
t.fit('includes the foreign persistent notification', async () => {
const displayedNotifications = await Notifications.getPresentedNotificationsAsync();
t.expect(displayedNotifications).toContain(
t.jasmine.objectContaining({
request: t.jasmine.objectContaining({
identifier: t.jasmine.stringMatching(/^__expo_foreign_notification__#.*#\d+$/),
content: t.jasmine.objectContaining({
data: t.jasmine.objectContaining({
'android.contains.customView': true,
}),
}),
}),
})
);
});
}
});
t.describe('dismissNotificationAsync()', () => {
t.it('resolves for a valid notification ID', async () => {
const identifier = 'test-id';
await Notifications.presentNotificationAsync({
identifier,
title: 'Sample title',
subtitle: 'What an event!',
body: 'An interesting event has just happened',
badge: 1,
});
await Notifications.dismissNotificationAsync(identifier);
});
t.it('resolves for an invalid notification ID', async () => {
await Notifications.dismissNotificationAsync('no-such-notification-id');
});
});
t.describe('dismissAllNotificationsAsync()', () => {
t.it('resolves', async () => {
await Notifications.dismissAllNotificationsAsync();
});
});
t.describe('getAllScheduledNotificationsAsync', () => {
const identifier = 'test-scheduled-notification';
const notification = { title: 'Scheduled notification' };
t.afterEach(async () => {
await Notifications.cancelScheduledNotificationAsync(identifier);
});
t.it('resolves with an Array', async () => {
const notifications = await Notifications.getAllScheduledNotificationsAsync();
t.expect(notifications).toEqual(t.jasmine.arrayContaining([]));
});
t.it('contains a scheduled notification', async () => {
const trigger = {
seconds: 10,
};
await Notifications.scheduleNotificationAsync({
identifier,
content: notification,
trigger,
});
const notifications = await Notifications.getAllScheduledNotificationsAsync();
t.expect(notifications).toContain(
t.jasmine.objectContaining({
identifier,
content: t.jasmine.objectContaining(notification),
trigger: t.jasmine.objectContaining({
repeats: false,
seconds: trigger.seconds,
type: 'timeInterval',
}),
})
);
});
t.it('does not contain a canceled notification', async () => {
const trigger = {
seconds: 10,
};
await Notifications.scheduleNotificationAsync({
identifier,
content: notification,
trigger,
});
await Notifications.cancelScheduledNotificationAsync(identifier);
const notifications = await Notifications.getAllScheduledNotificationsAsync();
t.expect(notifications).not.toContain(t.jasmine.objectContaining({ identifier }));
});
});
t.describe('scheduleNotificationAsync', () => {
const identifier = 'test-scheduled-notification';
const notification = {
title: 'Scheduled notification',
data: { key: 'value' },
badge: 2,
vibrate: [100, 100, 100, 100, 100, 100],
color: '#FF0000',
};
t.afterEach(async () => {
await Notifications.cancelScheduledNotificationAsync(identifier);
});
t.it(
'triggers a notification which emits an event',
async () => {
const notificationReceivedSpy = t.jasmine.createSpy('notificationReceived');
const subscription = Notifications.addNotificationReceivedListener(
notificationReceivedSpy
);
await Notifications.scheduleNotificationAsync({
identifier,
content: notification,
trigger: { seconds: 5 },
});
await waitFor(6000);
t.expect(notificationReceivedSpy).toHaveBeenCalled();
subscription.remove();
},
10000
);
t.it(
'throws an error if a user defines an invalid trigger (no repeats)',
async () => {
let error = undefined;
try {
await Notifications.scheduleNotificationAsync({
identifier,
content: notification,
trigger: { seconds: 5, hour: 2 },
});
} catch (err) {
error = err;
}
t.expect(error).toBeDefined();
},
10000
);
t.it(
'throws an error if a user defines an invalid trigger (with repeats)',
async () => {
let error = undefined;
try {
await Notifications.scheduleNotificationAsync({
identifier,
content: notification,
trigger: { seconds: 5, repeats: true, hour: 2 },
});
} catch (err) {
error = err;
}
t.expect(error).toBeDefined();
},
10000
);
t.it(
'triggers a notification which contains the custom color',
async () => {
const notificationReceivedSpy = t.jasmine.createSpy('notificationReceived');
const subscription = Notifications.addNotificationReceivedListener(
notificationReceivedSpy
);
await Notifications.scheduleNotificationAsync({
identifier,
content: notification,
trigger: { seconds: 5 },
});
await waitFor(6000);
t.expect(notificationReceivedSpy).toHaveBeenCalled();
if (Platform.OS === 'android') {
t.expect(notificationReceivedSpy).toHaveBeenCalledWith(
t.jasmine.objectContaining({
request: t.jasmine.objectContaining({
content: t.jasmine.objectContaining({
// #AARRGGBB
color: '#FFFF0000',
}),
}),
})
);
}
subscription.remove();
},
10000
);
t.it(
'triggers a notification which triggers the handler (`seconds` trigger)',
async () => {
let notificationFromEvent = undefined;
Notifications.setNotificationHandler({
handleNotification: async event => {
notificationFromEvent = event;
return {
shouldShowAlert: true,
};
},
});
await Notifications.scheduleNotificationAsync({
identifier,
content: notification,
trigger: { seconds: 5 },
});
await waitFor(6000);
t.expect(notificationFromEvent).toBeDefined();
Notifications.setNotificationHandler(null);
},
10000
);
t.it(
'triggers a notification which triggers the handler (with custom sound)',
async () => {
let notificationFromEvent = undefined;
Notifications.setNotificationHandler({
handleNotification: async event => {
notificationFromEvent = event;
return {
shouldShowAlert: true,
shouldPlaySound: true,
};
},
});
await Notifications.scheduleNotificationAsync({
identifier,
content: {
...notification,
sound: 'notification.wav',
},
trigger: { seconds: 5 },
});
await waitFor(6000);
t.expect(notificationFromEvent).toBeDefined();
t.expect(notificationFromEvent).toEqual(
t.jasmine.objectContaining({
request: t.jasmine.objectContaining({
content: t.jasmine.objectContaining({
sound: 'custom',
}),
}),
})
);
Notifications.setNotificationHandler(null);
},
10000
);
t.it(
'triggers a notification which triggers the handler (with custom sound set, but not existent)',
async () => {
let notificationFromEvent = undefined;
Notifications.setNotificationHandler({
handleNotification: async event => {
notificationFromEvent = event;
return {
shouldShowAlert: true,
shouldPlaySound: true,
};
},
});
await Notifications.scheduleNotificationAsync({
identifier,
content: {
...notification,
sound: 'no-such-file.wav',
},
trigger: { seconds: 5 },
});
await waitFor(6000);
t.expect(notificationFromEvent).toBeDefined();
t.expect(notificationFromEvent).toEqual(
t.jasmine.objectContaining({
request: t.jasmine.objectContaining({
content: t.jasmine.objectContaining({
sound: 'custom',
}),
}),
})
);
Notifications.setNotificationHandler(null);
},
10000
);
t.it(
'triggers a notification which triggers the handler (`Date` trigger)',
async () => {
let notificationFromEvent = undefined;
Notifications.setNotificationHandler({
handleNotification: async event => {
notificationFromEvent = event;
return {
shouldShowAlert: true,
};
},
});
const trigger = new Date(Date.now() + 5 * 1000);
await Notifications.scheduleNotificationAsync({
identifier,
content: notification,
trigger,
});
await waitFor(6000);
t.expect(notificationFromEvent).toBeDefined();
Notifications.setNotificationHandler(null);
},
10000
);
t.it(
'schedules a repeating daily notification. only first scheduled event is verified.',
async () => {