-
Notifications
You must be signed in to change notification settings - Fork 374
Expand file tree
/
Copy pathoffline-feature.js
More file actions
1620 lines (1380 loc) · 63.4 KB
/
offline-feature.js
File metadata and controls
1620 lines (1380 loc) · 63.4 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
/* eslint-disable no-underscore-dangle */
import React from 'react';
import { Text, View } from 'react-native';
import { act, cleanup, render, screen, waitFor } from '@testing-library/react-native';
import { v4 as uuidv4 } from 'uuid';
import { ChannelList } from '../../components/ChannelList/ChannelList';
import { Chat } from '../../components/Chat/Chat';
import { useChannelsContext } from '../../contexts/channelsContext/ChannelsContext';
import { getOrCreateChannelApi } from '../../mock-builders/api/getOrCreateChannel';
import { queryChannelsApi } from '../../mock-builders/api/queryChannels';
import { useMockedApis } from '../../mock-builders/api/useMockedApis';
import dispatchChannelDeletedEvent from '../../mock-builders/event/channelDeleted';
import dispatchChannelHiddenEvent from '../../mock-builders/event/channelHidden';
import dispatchChannelTruncatedEvent from '../../mock-builders/event/channelTruncated';
import dispatchChannelUpdatedEvent from '../../mock-builders/event/channelUpdated';
import dispatchChannelVisibleEvent from '../../mock-builders/event/channelVisible';
import dispatchConnectionChangedEvent from '../../mock-builders/event/connectionChanged';
import dispatchMemberAddedEvent from '../../mock-builders/event/memberAdded';
import dispatchMemberRemovedEvent from '../../mock-builders/event/memberRemoved';
import dispatchMemberUpdatedEvent from '../../mock-builders/event/memberUpdated';
import dispatchMessageNewEvent from '../../mock-builders/event/messageNew';
import dispatchMessageReadEvent from '../../mock-builders/event/messageRead';
import dispatchMessageUpdatedEvent from '../../mock-builders/event/messageUpdated';
import dispatchNotificationAddedToChannel from '../../mock-builders/event/notificationAddedToChannel';
import dispatchNotificationMarkUnread from '../../mock-builders/event/notificationMarkUnread';
import dispatchNotificationMessageNewEvent from '../../mock-builders/event/notificationMessageNew';
import dispatchNotificationRemovedFromChannel from '../../mock-builders/event/notificationRemovedFromChannel';
import dispatchReactionDeletedEvent from '../../mock-builders/event/reactionDeleted';
import dispatchReactionNewEvent from '../../mock-builders/event/reactionNew';
import dispatchReactionUpdatedEvent from '../../mock-builders/event/reactionUpdated';
import { generateChannelResponse } from '../../mock-builders/generator/channel';
import { generateMember } from '../../mock-builders/generator/member';
import { generateMessage } from '../../mock-builders/generator/message';
import { generateReaction } from '../../mock-builders/generator/reaction';
import { generateUser } from '../../mock-builders/generator/user';
import { getTestClientWithUser } from '../../mock-builders/mock';
import { convertFilterSortToQuery } from '../../store/apis/utils/convertFilterSortToQuery';
import { tables } from '../../store/schema';
import { BetterSqlite } from '../../test-utils/BetterSqlite';
/**
* We are gonna use following custom UI components for preview and list.
* If we use ChannelPreviewView or ChannelPreviewLastMessage here, then changes
* to those components might end up breaking tests for ChannelList, which will be quite painful
* to debug.
*/
const ChannelPreviewComponent = ({ channel, setActiveChannel }) => (
<View accessibilityLabel='list-item' onPress={setActiveChannel} testID={channel.cid}>
<Text>{channel.data.name}</Text>
<Text>{channel.state.messages[0]?.text}</Text>
</View>
);
const ChannelListComponent = (props) => {
const { channels, onSelect } = useChannelsContext();
if (!channels) {
return null;
}
return (
<View testID='channel-list'>
{channels?.map((channel) => (
<ChannelPreviewComponent
{...props}
channel={channel}
key={channel.id}
setActiveChannel={onSelect}
/>
))}
</View>
);
};
test('Workaround to allow exporting tests', () => expect(true).toBe(true));
export const Generic = () => {
describe('Offline support is disabled', () => {
let chatClient;
beforeAll(async () => {
jest.clearAllMocks();
chatClient = await getTestClientWithUser({ id: 'dan' });
await BetterSqlite.openDB();
BetterSqlite.dropAllTables();
});
afterAll(() => {
BetterSqlite.dropAllTables();
BetterSqlite.closeDB();
cleanup();
jest.clearAllMocks();
});
it('should NOT create tables on first load if offline feature is disabled', async () => {
render(
<Chat client={chatClient}>
<View testID='test-child' />
</Chat>,
);
await waitFor(() => expect(screen.getByTestId('test-child')).toBeTruthy());
await waitFor(async () => {
const tablesInDb = await BetterSqlite.getTables();
const tableNamesInDB = tablesInDb.map((table) => table.name);
const tablesNamesInSchema = Object.keys(tables);
tablesNamesInSchema.forEach((name) => {
expect(tableNamesInDB.includes(name)).toBe(false);
});
});
});
});
describe('Offline support is enabled', () => {
let chatClient;
let channels;
let allUsers;
let allMessages;
let allMembers;
let allReactions;
let allReads;
const getRandomInt = (lower, upper) => Math.floor(lower + Math.random() * (upper - lower + 1));
const createChannel = (messagesOverride) => {
const id = uuidv4();
const cid = `messaging:${id}`;
// always guarantee at least 2 members for ease of use; cases that need to test specific behaviour
// for 1 or 0 member channels should explicitly generate them.
const begin = getRandomInt(0, allUsers.length - 3); // begin shouldn't be the end of users.length
const end = getRandomInt(begin + 2, allUsers.length - 1);
const usersForMembers = allUsers.slice(begin, end);
const members = usersForMembers.map((user) =>
generateMember({
cid,
user,
}),
);
members.push(generateMember({ cid, user: chatClient.user }));
const messages =
messagesOverride ||
Array(10)
.fill(1)
.map(() => {
const id = uuidv4();
const user = usersForMembers[getRandomInt(0, usersForMembers.length - 1)];
const begin = getRandomInt(0, usersForMembers.length - 2); // begin shouldn't be the end of users.length
const end = getRandomInt(begin + 1, usersForMembers.length - 1);
const usersForReactions = usersForMembers.slice(begin, end);
const reactions = usersForReactions.map((user) =>
generateReaction({
message_id: id,
user,
}),
);
allReactions.push(...reactions);
return generateMessage({
cid,
id,
latest_reactions: reactions,
user,
userId: user.id,
});
});
const reads = members.map((member) => ({
cid,
last_read: new Date(new Date().setDate(new Date().getDate() - getRandomInt(0, 20))),
unread_messages: 0,
user: member.user,
}));
allMessages.push(...messages);
allMembers.push(...members);
allReads.push(...reads);
return generateChannelResponse({
cid,
id,
members,
messages,
read: reads,
});
};
beforeEach(async () => {
jest.clearAllMocks();
chatClient = await getTestClientWithUser({ id: 'dan' });
allUsers = Array(20).fill(1).map(generateUser);
allUsers.push(chatClient.user);
allMessages = [];
allMembers = [];
allReactions = [];
allReads = [];
channels = Array(10)
.fill(1)
.map(() => createChannel());
await BetterSqlite.openDB();
BetterSqlite.dropAllTables();
});
afterEach(() => {
BetterSqlite.dropAllTables();
BetterSqlite.closeDB();
cleanup();
jest.clearAllMocks();
});
const filters = {
foo: 'bar',
type: 'messaging',
};
const sort = { last_updated: 1 };
const renderComponent = () =>
render(
<Chat client={chatClient} enableOfflineSupport>
<ChannelList
filters={filters}
List={ChannelListComponent}
Preview={ChannelPreviewComponent}
sort={sort}
/>
</Chat>,
);
const expectCIDsOnUIToBeInDB = async (queryAllByLabelText) => {
const channelIdsOnUI = queryAllByLabelText('list-item').map(
(node) => node._fiber.pendingProps.testID,
);
await waitFor(async () => {
const channelQueriesRows = await BetterSqlite.selectFromTable('channelQueries');
const cidsInDB = JSON.parse(channelQueriesRows[0].cids);
const filterSortQueryInDB = channelQueriesRows[0].id;
const actualFilterSortQueryInDB = convertFilterSortToQuery({ filters, sort });
expect(channelQueriesRows.length).toBe(1);
expect(filterSortQueryInDB).toBe(actualFilterSortQueryInDB);
expect(cidsInDB.length).toBe(channelIdsOnUI.length);
channelIdsOnUI.forEach((cidOnUi, index) => {
expect(cidsInDB.includes(cidOnUi)).toBe(true);
expect(index).toBe(cidsInDB.indexOf(cidOnUi));
});
});
};
const expectAllChannelsWithStateToBeInDB = async (queryAllByLabelText) => {
const channelIdsOnUI = queryAllByLabelText('list-item').map(
(node) => node._fiber.pendingProps.testID,
);
await waitFor(async () => {
const channelsRows = await BetterSqlite.selectFromTable('channels');
const messagesRows = await BetterSqlite.selectFromTable('messages');
const membersRows = await BetterSqlite.selectFromTable('members');
const usersRows = await BetterSqlite.selectFromTable('users');
const reactionsRows = await BetterSqlite.selectFromTable('reactions');
const readsRows = await BetterSqlite.selectFromTable('reads');
expect(channelIdsOnUI.length).toBe(channels.length);
expect(channelsRows.length).toBe(channels.length);
expect(messagesRows.length).toBe(allMessages.length);
expect(membersRows.length).toBe(allMembers.length);
expect(reactionsRows.length).toBe(allReactions.length);
channelsRows.forEach((row) => {
expect(channelIdsOnUI.includes(row.cid)).toBe(true);
});
messagesRows.forEach((row) => {
expect(allMessages.filter((m) => m.id === row.id)).toHaveLength(1);
});
membersRows.forEach((row) =>
expect(
allMembers.filter((m) => m.cid === row.cid && m.user.id === row.userId),
).toHaveLength(1),
);
usersRows.forEach((row) => expect(allUsers.filter((u) => u.id === row.id)).toHaveLength(1));
reactionsRows.forEach((row) =>
expect(
allReactions.filter((r) => r.message_id === row.messageId && row.userId === r.user_id),
).toHaveLength(1),
);
readsRows.forEach((row) =>
expect(
allReads.filter((r) => r.user.id === row.userId && r.cid === row.cid),
).toHaveLength(1),
);
});
};
it('should create tables on first load if offline feature is enabled', async () => {
render(
<Chat client={chatClient} enableOfflineSupport>
<View testID='test-child' />
</Chat>,
);
await waitFor(() => expect(screen.getByTestId('test-child')).toBeTruthy());
const tablesInDb = await BetterSqlite.getTables();
const tableNamesInDB = tablesInDb.map((table) => table.name);
const tablesNamesInSchema = Object.keys(tables);
tablesNamesInSchema.forEach((name) => expect(tableNamesInDB.includes(name)).toBe(true));
});
it('should store filter-sort query and cids on ChannelList in channelQueries table', async () => {
useMockedApis(chatClient, [queryChannelsApi(channels)]);
renderComponent();
await act(() => dispatchConnectionChangedEvent(chatClient, false));
// await waiter();
await act(() => dispatchConnectionChangedEvent(chatClient));
await act(async () => await chatClient.offlineDb.syncManager.invokeSyncStatusListeners(true));
await waitFor(async () => {
expect(screen.getByTestId('channel-list')).toBeTruthy();
await expectCIDsOnUIToBeInDB(screen.queryAllByLabelText);
});
});
it('should store channels and its state in tables', async () => {
useMockedApis(chatClient, [queryChannelsApi(channels)]);
renderComponent();
act(() => dispatchConnectionChangedEvent(chatClient));
await act(async () => await chatClient.offlineDb.syncManager.invokeSyncStatusListeners(true));
await waitFor(async () => {
expect(screen.getByTestId('channel-list')).toBeTruthy();
await expectAllChannelsWithStateToBeInDB(screen.queryAllByLabelText);
});
});
it('should fetch channels from the db correctly even if they are empty', async () => {
const emptyChannel = createChannel([]);
useMockedApis(chatClient, [queryChannelsApi([emptyChannel])]);
jest.spyOn(chatClient, 'hydrateActiveChannels');
renderComponent();
await waitFor(async () => {
act(() => dispatchConnectionChangedEvent(chatClient));
await act(
async () => await chatClient.offlineDb.syncManager.invokeSyncStatusListeners(true),
);
expect(screen.getByTestId('channel-list')).toBeTruthy();
expect(screen.getByTestId(emptyChannel.cid)).toBeTruthy();
expect(chatClient.hydrateActiveChannels).toHaveBeenCalled();
expect(chatClient.hydrateActiveChannels.mock.calls[0][0]).toStrictEqual([emptyChannel]);
});
});
it('should add a new message to database', async () => {
useMockedApis(chatClient, [queryChannelsApi(channels)]);
renderComponent();
act(() => dispatchConnectionChangedEvent(chatClient));
await act(async () => await chatClient.offlineDb.syncManager.invokeSyncStatusListeners(true));
await waitFor(() => expect(screen.getByTestId('channel-list')).toBeTruthy());
const targetChannel = channels[0].channel;
const newMessage = generateMessage({
cid: targetChannel.cid,
user: generateUser(),
});
act(() => dispatchMessageNewEvent(chatClient, newMessage, targetChannel));
await waitFor(async () => {
const messagesRows = await BetterSqlite.selectFromTable('messages');
const readRows = await BetterSqlite.selectFromTable('reads');
const matchingMessageRows = messagesRows.filter((m) => m.id === newMessage.id);
const matchingReadRows = readRows.filter(
(r) => targetChannel.cid === r.cid && chatClient.userID === r.userId,
);
expect(matchingMessageRows.length).toBe(1);
expect(matchingMessageRows[0].id).toBe(newMessage.id);
expect(matchingReadRows.length).toBe(1);
expect(matchingReadRows[0].unreadMessages).toBe(1);
});
});
it('should correctly handle multiple new messages and add them to the database', async () => {
useMockedApis(chatClient, [queryChannelsApi(channels)]);
renderComponent();
act(() => dispatchConnectionChangedEvent(chatClient));
await act(async () => await chatClient.offlineDb.syncManager.invokeSyncStatusListeners(true));
await waitFor(() => expect(screen.getByTestId('channel-list')).toBeTruthy());
const targetChannel = channels[0].channel;
// check if the reads state is correct first
await waitFor(async () => {
const readRows = await BetterSqlite.selectFromTable('reads');
const matchingReadRows = readRows.filter(
(r) => targetChannel.cid === r.cid && chatClient.userID === r.userId,
);
expect(matchingReadRows.length).toBe(1);
expect(matchingReadRows[0].unreadMessages).toBe(0);
});
const newMessages = [
generateMessage({
cid: targetChannel.cid,
user: generateUser(),
}),
generateMessage({
cid: targetChannel.cid,
user: generateUser(),
}),
generateMessage({
cid: targetChannel.cid,
user: generateUser(),
}),
];
newMessages.forEach((newMessage) => {
act(() => dispatchMessageNewEvent(chatClient, newMessage, targetChannel));
});
await waitFor(async () => {
const messagesRows = await BetterSqlite.selectFromTable('messages');
const readRows = await BetterSqlite.selectFromTable('reads');
const matchingMessageRows = messagesRows.filter((m) =>
newMessages.some((newMessage) => newMessage.id === m.id),
);
const matchingReadRows = readRows.filter(
(r) => targetChannel.cid === r.cid && chatClient.userID === r.userId,
);
expect(matchingMessageRows.length).toBe(3);
newMessages.forEach((newMessage) => {
expect(
matchingMessageRows.some(
(matchingMessageRow) => matchingMessageRow.id === newMessage.id,
),
).toBe(true);
});
expect(matchingReadRows.length).toBe(1);
expect(matchingReadRows[0].unreadMessages).toBe(3);
});
});
it('should correctly handle multiple new messages from our own user', async () => {
useMockedApis(chatClient, [queryChannelsApi(channels)]);
renderComponent();
act(() => dispatchConnectionChangedEvent(chatClient));
await act(async () => await chatClient.offlineDb.syncManager.invokeSyncStatusListeners(true));
await waitFor(() => expect(screen.getByTestId('channel-list')).toBeTruthy());
const targetChannel = channels[0].channel;
// check if the reads state is correct first
await waitFor(async () => {
const readRows = await BetterSqlite.selectFromTable('reads');
const matchingReadRows = readRows.filter(
(r) => targetChannel.cid === r.cid && chatClient.userID === r.userId,
);
expect(matchingReadRows.length).toBe(1);
expect(matchingReadRows[0].unreadMessages).toBe(0);
});
const newMessages = [
generateMessage({
cid: targetChannel.cid,
user: chatClient.user,
}),
generateMessage({
cid: targetChannel.cid,
user: chatClient.user,
}),
generateMessage({
cid: targetChannel.cid,
user: chatClient.user,
}),
];
newMessages.forEach((newMessage) => {
act(() => dispatchMessageNewEvent(chatClient, newMessage, targetChannel));
});
await waitFor(async () => {
const messagesRows = await BetterSqlite.selectFromTable('messages');
const readRows = await BetterSqlite.selectFromTable('reads');
const matchingMessageRows = messagesRows.filter((m) =>
newMessages.some((newMessage) => newMessage.id === m.id),
);
const matchingReadRows = readRows.filter(
(r) => targetChannel.cid === r.cid && chatClient.userID === r.userId,
);
expect(matchingMessageRows.length).toBe(3);
newMessages.forEach((newMessage) => {
expect(
matchingMessageRows.some(
(matchingMessageRow) => matchingMessageRow.id === newMessage.id,
),
).toBe(true);
});
expect(matchingReadRows.length).toBe(1);
expect(matchingReadRows[0].unreadMessages).toBe(0);
});
});
it('should add a new channel and a new message to database from notification event', async () => {
useMockedApis(chatClient, [queryChannelsApi(channels)]);
renderComponent();
act(() => dispatchConnectionChangedEvent(chatClient));
await act(async () => await chatClient.offlineDb.syncManager.invokeSyncStatusListeners(true));
await waitFor(() => {
expect(screen.getByTestId('channel-list')).toBeTruthy();
});
const newChannel = createChannel();
channels.push(newChannel);
useMockedApis(chatClient, [getOrCreateChannelApi(newChannel)]);
await act(() => dispatchNotificationMessageNewEvent(chatClient, newChannel.channel));
await waitFor(() => {
const channelIdsOnUI = screen
.queryAllByLabelText('list-item')
.map((node) => node._fiber.pendingProps.testID);
expect(channelIdsOnUI.includes(newChannel.channel.cid)).toBeTruthy();
});
await expectAllChannelsWithStateToBeInDB(screen.queryAllByLabelText);
});
it('should update a message in database', async () => {
useMockedApis(chatClient, [queryChannelsApi(channels)]);
renderComponent();
act(() => dispatchConnectionChangedEvent(chatClient));
await act(async () => await chatClient.offlineDb.syncManager.invokeSyncStatusListeners(true));
await waitFor(() => expect(screen.getByTestId('channel-list')).toBeTruthy());
const updatedMessage = { ...channels[0].messages[0] };
updatedMessage.text = uuidv4();
act(() => dispatchMessageUpdatedEvent(chatClient, updatedMessage, channels[0].channel));
await waitFor(async () => {
const messagesRows = await BetterSqlite.selectFromTable('messages');
const matchingRows = messagesRows.filter((m) => m.id === updatedMessage.id);
expect(matchingRows.length).toBe(1);
expect(matchingRows[0].text).toBe(updatedMessage.text);
});
});
it('should remove the channel from DB when user is removed as member', async () => {
useMockedApis(chatClient, [queryChannelsApi(channels)]);
renderComponent();
act(() => dispatchConnectionChangedEvent(chatClient));
await act(async () => await chatClient.offlineDb.syncManager.invokeSyncStatusListeners(true));
await waitFor(() => expect(screen.getByTestId('channel-list')).toBeTruthy());
const removedChannel = channels[getRandomInt(0, channels.length - 1)].channel;
act(() => dispatchNotificationRemovedFromChannel(chatClient, removedChannel));
await waitFor(async () => {
const channelIdsOnUI = screen
.queryAllByLabelText('list-item')
.map((node) => node._fiber.pendingProps.testID);
expect(channelIdsOnUI.includes(removedChannel.cid)).toBeFalsy();
await expectCIDsOnUIToBeInDB(screen.queryAllByLabelText);
const channelsRows = await BetterSqlite.selectFromTable('channels');
const matchingRows = channelsRows.filter((c) => c.id === removedChannel.id);
const messagesRows = await BetterSqlite.selectFromTable('messages');
const matchingMessagesRows = messagesRows.filter((m) => m.cid === removedChannel.cid);
expect(matchingRows.length).toBe(0);
expect(matchingMessagesRows.length).toBe(0);
});
});
it('should remove the channel from DB if the channel is deleted', async () => {
useMockedApis(chatClient, [queryChannelsApi(channels)]);
renderComponent();
act(() => dispatchConnectionChangedEvent(chatClient));
await act(async () => await chatClient.offlineDb.syncManager.invokeSyncStatusListeners(true));
await waitFor(() => expect(screen.getByTestId('channel-list')).toBeTruthy());
const removedChannel = channels[getRandomInt(0, channels.length - 1)].channel;
act(() => dispatchChannelDeletedEvent(chatClient, removedChannel));
await waitFor(async () => {
const channelIdsOnUI = screen
.queryAllByLabelText('list-item')
.map((node) => node._fiber.pendingProps.testID);
expect(channelIdsOnUI.includes(removedChannel.cid)).toBeFalsy();
await expectCIDsOnUIToBeInDB(screen.queryAllByLabelText);
const channelsRows = await BetterSqlite.selectFromTable('channels');
const matchingRows = channelsRows.filter((c) => c.id === removedChannel.id);
const messagesRows = await BetterSqlite.selectFromTable('messages');
const matchingMessagesRows = messagesRows.filter((m) => m.cid === removedChannel.cid);
expect(matchingRows.length).toBe(0);
expect(matchingMessagesRows.length).toBe(0);
});
});
it('should correctly mark the channel as hidden in the db', async () => {
useMockedApis(chatClient, [queryChannelsApi(channels)]);
renderComponent();
act(() => dispatchConnectionChangedEvent(chatClient));
await act(async () => await chatClient.offlineDb.syncManager.invokeSyncStatusListeners(true));
await waitFor(() => expect(screen.getByTestId('channel-list')).toBeTruthy());
const hiddenChannel = channels[getRandomInt(0, channels.length - 1)].channel;
act(() => dispatchChannelHiddenEvent(chatClient, hiddenChannel));
await waitFor(async () => {
const channelIdsOnUI = screen
.queryAllByLabelText('list-item')
.map((node) => node._fiber.pendingProps.testID);
expect(channelIdsOnUI.includes(hiddenChannel.cid)).toBeFalsy();
await expectCIDsOnUIToBeInDB(screen.queryAllByLabelText);
const channelsRows = await BetterSqlite.selectFromTable('channels');
const matchingRows = channelsRows.filter((c) => c.id === hiddenChannel.id);
const messagesRows = await BetterSqlite.selectFromTable('messages');
const matchingMessagesRows = messagesRows.filter((m) => m.cid === hiddenChannel.cid);
expect(matchingRows.length).toBe(1);
expect(matchingRows[0].hidden).toBeTruthy();
expect(matchingMessagesRows.length).toBe(
chatClient.activeChannels[hiddenChannel.cid].state.messages.length,
);
});
});
it('should correctly mark the channel as visible if it was hidden before in the db', async () => {
useMockedApis(chatClient, [queryChannelsApi(channels)]);
renderComponent();
act(() => dispatchConnectionChangedEvent(chatClient));
await act(async () => await chatClient.offlineDb.syncManager.invokeSyncStatusListeners(true));
await waitFor(() => expect(screen.getByTestId('channel-list')).toBeTruthy());
const hiddenChannel = channels[getRandomInt(0, channels.length - 1)].channel;
// first, we mark it as hidden
act(() => dispatchChannelHiddenEvent(chatClient, hiddenChannel));
await waitFor(async () => {
const channelIdsOnUI = screen
.queryAllByLabelText('list-item')
.map((node) => node._fiber.pendingProps.testID);
expect(channelIdsOnUI.includes(hiddenChannel.cid)).toBeFalsy();
await expectCIDsOnUIToBeInDB(screen.queryAllByLabelText);
const channelsRows = await BetterSqlite.selectFromTable('channels');
const matchingRows = channelsRows.filter((c) => c.id === hiddenChannel.id);
const messagesRows = await BetterSqlite.selectFromTable('messages');
const matchingMessagesRows = messagesRows.filter((m) => m.cid === hiddenChannel.cid);
expect(matchingRows.length).toBe(1);
expect(matchingRows[0].hidden).toBeTruthy();
expect(matchingMessagesRows.length).toBe(
chatClient.activeChannels[hiddenChannel.cid].state.messages.length,
);
});
// then, we make it visible after waiting for everything to finish
act(() => dispatchChannelVisibleEvent(chatClient, hiddenChannel));
await waitFor(async () => {
const channelIdsOnUI = screen
.queryAllByLabelText('list-item')
.map((node) => node._fiber.pendingProps.testID);
expect(channelIdsOnUI.includes(hiddenChannel.cid)).toBeFalsy();
await expectCIDsOnUIToBeInDB(screen.queryAllByLabelText);
const channelsRows = await BetterSqlite.selectFromTable('channels');
const matchingRows = channelsRows.filter((c) => c.id === hiddenChannel.id);
const messagesRows = await BetterSqlite.selectFromTable('messages');
const matchingMessagesRows = messagesRows.filter((m) => m.cid === hiddenChannel.cid);
expect(matchingRows.length).toBe(1);
expect(matchingRows[0].hidden).toBeFalsy();
expect(matchingMessagesRows.length).toBe(
chatClient.activeChannels[hiddenChannel.cid].state.messages.length,
);
});
});
it('should add the channel to DB when user is added as member', async () => {
useMockedApis(chatClient, [queryChannelsApi(channels)]);
renderComponent();
act(() => dispatchConnectionChangedEvent(chatClient));
await act(async () => await chatClient.offlineDb.syncManager.invokeSyncStatusListeners(true));
await waitFor(() => expect(screen.getByTestId('channel-list')).toBeTruthy());
const newChannel = createChannel();
useMockedApis(chatClient, [getOrCreateChannelApi(newChannel)]);
act(() => dispatchNotificationAddedToChannel(chatClient, newChannel.channel));
await waitFor(async () => {
const channelIdsOnUI = screen
.queryAllByLabelText('list-item')
.map((node) => node._fiber.pendingProps.testID);
expect(channelIdsOnUI.includes(newChannel.channel.cid)).toBeTruthy();
await expectCIDsOnUIToBeInDB(screen.queryAllByLabelText);
const channelsRows = await BetterSqlite.selectFromTable('channels');
const matchingChannelsRows = channelsRows.filter((c) => c.id === newChannel.channel.id);
const messagesRows = await BetterSqlite.selectFromTable('messages');
const matchingMessagesRows = messagesRows.filter((m) => m.cid === newChannel.channel.cid);
expect(matchingChannelsRows.length).toBe(1);
expect(matchingMessagesRows.length).toBe(newChannel.messages.length);
});
});
it('should remove the channel messages from DB when channel is truncated', async () => {
useMockedApis(chatClient, [queryChannelsApi(channels)]);
renderComponent();
act(() => dispatchConnectionChangedEvent(chatClient));
await act(async () => await chatClient.offlineDb.syncManager.invokeSyncStatusListeners(true));
await waitFor(() => expect(screen.getByTestId('channel-list')).toBeTruthy());
const channelToTruncate = channels[getRandomInt(0, channels.length - 1)].channel;
act(() => dispatchChannelTruncatedEvent(chatClient, channelToTruncate));
await waitFor(async () => {
const channelIdsOnUI = screen
.queryAllByLabelText('list-item')
.map((node) => node._fiber.pendingProps.testID);
expect(channelIdsOnUI.includes(channelToTruncate.cid)).toBeTruthy();
expectCIDsOnUIToBeInDB(screen.queryAllByLabelText);
const messagesRows = await BetterSqlite.selectFromTable('messages');
const matchingMessagesRows = messagesRows.filter((m) => m.cid === channelToTruncate.cid);
const readsRows = await BetterSqlite.selectFromTable('reads');
const matchingReadRows = readsRows.filter(
(r) => r.userId === chatClient.userID && r.cid === channelToTruncate.cid,
);
expect(matchingMessagesRows.length).toBe(0);
expect(matchingReadRows.length).toBe(1);
expect(matchingReadRows[0].unreadMessages).toBe(0);
});
});
it('should truncate the correct messages if channel.truncated arrives with truncated_at', async () => {
useMockedApis(chatClient, [queryChannelsApi(channels)]);
renderComponent();
act(() => dispatchConnectionChangedEvent(chatClient));
await act(async () => await chatClient.offlineDb.syncManager.invokeSyncStatusListeners(true));
await waitFor(() => expect(screen.getByTestId('channel-list')).toBeTruthy());
const channelResponse = channels[getRandomInt(0, channels.length - 1)];
const channelToTruncate = channelResponse.channel;
const messages = channelResponse.messages;
messages.sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
// truncate at the middle
const truncatedAt = messages[Number(messages.length / 2)].created_at;
act(() =>
dispatchChannelTruncatedEvent(chatClient, {
...channelToTruncate,
truncated_at: truncatedAt,
}),
);
await waitFor(async () => {
const channelIdsOnUI = screen
.queryAllByLabelText('list-item')
.map((node) => node._fiber.pendingProps.testID);
expect(channelIdsOnUI.includes(channelToTruncate.cid)).toBeTruthy();
expectCIDsOnUIToBeInDB(screen.queryAllByLabelText);
const messagesRows = await BetterSqlite.selectFromTable('messages');
const matchingMessagesRows = messagesRows.filter((m) => m.cid === channelToTruncate.cid);
const readsRows = await BetterSqlite.selectFromTable('reads');
const matchingReadRows = readsRows.filter(
(r) => r.userId === chatClient.userID && r.cid === channelToTruncate.cid,
);
const messagesLeft = messages.length / 2 - 1;
expect(matchingMessagesRows.length).toBe(messagesLeft);
expect(matchingReadRows.length).toBe(1);
expect(matchingReadRows[0].unreadMessages).toBe(messagesLeft);
});
});
it('should gracefully handle a truncated_at date before each message', async () => {
useMockedApis(chatClient, [queryChannelsApi(channels)]);
renderComponent();
act(() => dispatchConnectionChangedEvent(chatClient));
await act(async () => await chatClient.offlineDb.syncManager.invokeSyncStatusListeners(true));
await waitFor(() => expect(screen.getByTestId('channel-list')).toBeTruthy());
const channelResponse = channels[getRandomInt(0, channels.length - 1)];
const channelToTruncate = channelResponse.channel;
const truncatedAt = new Date(0).toISOString();
act(() =>
dispatchChannelTruncatedEvent(chatClient, {
...channelToTruncate,
truncated_at: truncatedAt,
}),
);
await waitFor(async () => {
const channelIdsOnUI = screen
.queryAllByLabelText('list-item')
.map((node) => node._fiber.pendingProps.testID);
expect(channelIdsOnUI.includes(channelToTruncate.cid)).toBeTruthy();
expectCIDsOnUIToBeInDB(screen.queryAllByLabelText);
const messagesRows = await BetterSqlite.selectFromTable('messages');
const matchingMessagesRows = messagesRows.filter((m) => m.cid === channelToTruncate.cid);
expect(matchingMessagesRows.length).toBe(channelResponse.messages.length);
});
});
it('should gracefully handle a truncated_at date after each message', async () => {
useMockedApis(chatClient, [queryChannelsApi(channels)]);
renderComponent();
act(() => dispatchConnectionChangedEvent(chatClient));
await act(async () => await chatClient.offlineDb.syncManager.invokeSyncStatusListeners(true));
await waitFor(() => expect(screen.getByTestId('channel-list')).toBeTruthy());
const channelResponse = channels[getRandomInt(0, channels.length - 1)];
const channelToTruncate = channelResponse.channel;
const messages = channelResponse.messages;
const latestTimestamp = Math.max(...messages.map((m) => new Date(m.created_at).getTime()));
// truncate at the middle
const truncatedAt = new Date(latestTimestamp + 1).toISOString();
act(() =>
dispatchChannelTruncatedEvent(chatClient, {
...channelToTruncate,
truncated_at: truncatedAt,
}),
);
await waitFor(async () => {
const channelIdsOnUI = screen
.queryAllByLabelText('list-item')
.map((node) => node._fiber.pendingProps.testID);
expect(channelIdsOnUI.includes(channelToTruncate.cid)).toBeTruthy();
expectCIDsOnUIToBeInDB(screen.queryAllByLabelText);
const messagesRows = await BetterSqlite.selectFromTable('messages');
const matchingMessagesRows = messagesRows.filter((m) => m.cid === channelToTruncate.cid);
expect(matchingMessagesRows.length).toBe(0);
});
});
it('should add a reaction to DB when a new reaction is added', async () => {
useMockedApis(chatClient, [queryChannelsApi(channels)]);
renderComponent();
act(() => dispatchConnectionChangedEvent(chatClient));
await act(async () => await chatClient.offlineDb.syncManager.invokeSyncStatusListeners(true));
await waitFor(() => expect(screen.getByTestId('channel-list')).toBeTruthy());
const targetChannel = channels[getRandomInt(0, channels.length - 1)];
const targetMessage =
targetChannel.messages[getRandomInt(0, targetChannel.messages.length - 1)];
const reactionMember =
targetChannel.members[getRandomInt(0, targetChannel.members.length - 1)];
const newReaction = generateReaction({
message_id: targetMessage.id,
type: 'wow',
user: reactionMember.user,
});
const messageWithNewReaction = {
...targetMessage,
latest_reactions: [...targetMessage.latest_reactions, newReaction],
};
act(() =>
dispatchReactionNewEvent(
chatClient,
newReaction,
messageWithNewReaction,
targetChannel.channel,
),
);
await waitFor(async () => {
const reactionsRows = await BetterSqlite.selectFromTable('reactions');
const matchingReactionsRows = reactionsRows.filter(
(r) =>
r.type === newReaction.type &&
r.userId === reactionMember.user.id &&
r.messageId === messageWithNewReaction.id,
);
expect(matchingReactionsRows.length).toBe(1);
});
});
it('should correctly add multiple reactions to the DB', async () => {
useMockedApis(chatClient, [queryChannelsApi(channels)]);
renderComponent();
act(() => dispatchConnectionChangedEvent(chatClient));
await act(async () => await chatClient.offlineDb.syncManager.invokeSyncStatusListeners(true));
await waitFor(() => expect(screen.getByTestId('channel-list')).toBeTruthy());
const targetChannel = channels[getRandomInt(0, channels.length - 1)];
const targetMessage =
targetChannel.messages[getRandomInt(0, targetChannel.messages.length - 1)];
const reactionMember =
targetChannel.members[getRandomInt(0, targetChannel.members.length - 1)];
const someOtherMember = targetChannel.members.filter(
(member) => reactionMember.user.id !== member.user.id,
)[getRandomInt(0, targetChannel.members.length - 2)];
const newReactions = [
generateReaction({
message_id: targetMessage.id,
type: 'wow',
user: reactionMember.user,
}),
generateReaction({
message_id: targetMessage.id,
type: 'wow',
user: someOtherMember.user,
}),
generateReaction({
message_id: targetMessage.id,
type: 'love',
user: reactionMember.user,
}),
];
const messageWithNewReactionBase = {
...targetMessage,
latest_reactions: [...targetMessage.latest_reactions],
};
const newLatestReactions = [];
newReactions.forEach((newReaction) => {
newLatestReactions.push(newReaction);
const messageWithNewReaction = {
...messageWithNewReactionBase,
latest_reactions: [...messageWithNewReactionBase.latest_reactions, ...newLatestReactions],
};
act(() =>
dispatchReactionNewEvent(
chatClient,
newReaction,
messageWithNewReaction,
targetChannel.channel,
),
);
});
const finalReactionCount =
messageWithNewReactionBase.latest_reactions.length +
newReactions.filter(
(newReaction) =>
!messageWithNewReactionBase.latest_reactions.some(
(initialReaction) =>
initialReaction.type === newReaction.type &&
initialReaction.user.id === newReaction.user.id,
),
).length;
await waitFor(async () => {
const reactionsRows = await BetterSqlite.selectFromTable('reactions');
const matchingReactionsRows = reactionsRows.filter(
(r) => r.messageId === messageWithNewReactionBase.id,
);
expect(matchingReactionsRows.length).toBe(finalReactionCount);
newReactions.forEach((newReaction) => {
expect(
matchingReactionsRows.filter(
(reaction) =>
reaction.type === newReaction.type && reaction.userId === newReaction.user.id,
).length,
).toBe(1);