-
Notifications
You must be signed in to change notification settings - Fork 285
/
Copy pathChannel.test.js
1920 lines (1719 loc) Β· 68.1 KB
/
Channel.test.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
import { nanoid } from 'nanoid';
import React, { useEffect } from 'react';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom';
import { Channel } from '../Channel';
import { Chat } from '../../Chat';
import { LoadingErrorIndicator } from '../../Loading';
import { useChannelActionContext } from '../../../context/ChannelActionContext';
import { useChannelStateContext } from '../../../context/ChannelStateContext';
import { ChatProvider, useChatContext } from '../../../context/ChatContext';
import { useComponentContext } from '../../../context/ComponentContext';
import {
generateChannel,
generateFileAttachment,
generateMember,
generateMessage,
generateScrapedDataAttachment,
generateUser,
getOrCreateChannelApi,
getTestClientWithUser,
initClientWithChannels,
sendMessageApi,
threadRepliesApi,
useMockedApis,
} from '../../../mock-builders';
import { MessageList } from '../../MessageList';
import { Thread } from '../../Thread';
import { MessageProvider } from '../../../context';
import { MessageActionsBox } from '../../MessageActions';
jest.mock('../../Loading', () => ({
LoadingErrorIndicator: jest.fn(() => <div />),
LoadingIndicator: jest.fn(() => <div>loading</div>),
}));
const queryChannelWithNewMessages = (newMessages, channel) =>
// generate new channel mock from existing channel with new messages added
getOrCreateChannelApi(
generateChannel({
channel: {
config: channel.getConfig(),
id: channel.id,
type: channel.type,
},
messages: newMessages,
}),
);
const MockAvatar = ({ name }) => (
<div className='avatar' data-testid='custom-avatar'>
{name}
</div>
);
// This component is used for performing effects in a component that consumes the contexts from Channel,
// i.e. making use of the callbacks & values provided by the Channel component.
// the effect is called every time channelContext changes
const CallbackEffectWithChannelContexts = ({ callback }) => {
const channelStateContext = useChannelStateContext();
const channelActionContext = useChannelActionContext();
const componentContext = useComponentContext();
// eslint-disable-next-line react-hooks/exhaustive-deps
const channelContext = {
...channelStateContext,
...channelActionContext,
...componentContext,
};
useEffect(() => {
callback(channelContext);
}, [callback, channelContext]);
return null;
};
// In order for ChannelInner to be rendered, we need to set the active channel first.
const ActiveChannelSetter = ({ activeChannel }) => {
const { setActiveChannel } = useChatContext();
useEffect(() => {
setActiveChannel(activeChannel);
}, [activeChannel]); // eslint-disable-line
return null;
};
const user = generateUser({ custom: 'custom-value', id: 'id', name: 'name' });
// create a full message state so that we can properly test `loadMore`
const messages = Array.from({ length: 25 }, () => generateMessage({ user }));
const pinnedMessages = [generateMessage({ pinned: true, user })];
const renderComponent = async (props = {}, callback = () => {}) => {
const { channel: channelFromProps, chatClient: chatClientFromProps, ...channelProps } = props;
let result;
await act(() => {
result = render(
<Chat client={chatClientFromProps}>
<ActiveChannelSetter activeChannel={channelFromProps} />
<Channel {...channelProps}>
{channelProps.children}
<CallbackEffectWithChannelContexts callback={callback} />
</Channel>
</Chat>,
);
});
return result;
};
const initClient = async () => {
const members = [generateMember({ user })];
const mockedChannel = generateChannel({
members,
messages,
pinnedMessages,
});
const chatClient = await getTestClientWithUser(user);
// eslint-disable-next-line react-hooks/rules-of-hooks
useMockedApis(chatClient, [getOrCreateChannelApi(mockedChannel)]);
const channel = chatClient.channel('messaging', mockedChannel.channel.id);
jest.spyOn(channel, 'getConfig').mockImplementation(() => mockedChannel.channel.config);
return { channel, chatClient };
};
describe('Channel', () => {
const MockMessageList = () => {
const { messages: channelMessages } = useChannelStateContext();
return channelMessages.map(
({ id, status, text }) => status !== 'failed' && <div key={id || nanoid()}>{text}</div>,
);
};
afterEach(() => {
jest.clearAllMocks();
});
it('should render the EmptyPlaceholder prop if the channel is not provided by the ChatContext', async () => {
// get rid of console warnings as they are expected - Channel reaches to ChatContext
jest.spyOn(console, 'warn').mockImplementationOnce(() => null);
render(
<ChatProvider
value={{
channelsQueryState: {
error: null,
queryInProgress: null,
setError: jest.fn(),
setQueryInProgress: jest.fn(),
},
}}
>
<Channel EmptyPlaceholder={<div>empty</div>} />
</ChatProvider>,
);
await waitFor(() => expect(screen.getByText('empty')).toBeInTheDocument());
});
it('should render channel content if channels query loads more channels', async () => {
const { channel, chatClient } = await initClient();
const childrenContent = 'Channel children';
await channel.watch();
render(
<ChatProvider
value={{
channelsQueryState: {
error: null,
queryInProgress: 'load-more',
setError: jest.fn(),
setQueryInProgress: jest.fn(),
},
client: chatClient,
}}
>
<Channel channel={channel}>{childrenContent}</Channel>
</ChatProvider>,
);
await waitFor(() => expect(screen.getByText(childrenContent)).toBeInTheDocument());
});
it('should render default loading indicator if channels query is in progress', async () => {
const childrenContent = 'Channel children';
const { asFragment } = render(
<ChatProvider
value={{
channelsQueryState: {
error: null,
queryInProgress: 'reload',
setError: jest.fn(),
setQueryInProgress: jest.fn(),
},
}}
>
<Channel>{childrenContent}</Channel>
</ChatProvider>,
);
await waitFor(() => expect(asFragment()).toMatchSnapshot());
});
it('should render empty channel container if channel does not have cid', async () => {
const { channel } = await initClient();
const childrenContent = 'Channel children';
const { cid, ...channelWithoutCID } = channel;
const { asFragment } = render(
<ChatProvider
value={{
channel: channelWithoutCID,
channelsQueryState: {
error: null,
queryInProgress: null,
setError: jest.fn(),
setQueryInProgress: jest.fn(),
},
}}
>
<Channel>{childrenContent}</Channel>
</ChatProvider>,
);
await waitFor(() => expect(asFragment()).toMatchSnapshot());
});
it('should render empty channel container if channels query failed', async () => {
const childrenContent = 'Channel children';
const { asFragment } = render(
<ChatProvider
value={{
channelsQueryState: {
error: new Error(),
queryInProgress: null,
setError: jest.fn(),
setQueryInProgress: jest.fn(),
},
}}
>
<Channel>{childrenContent}</Channel>
</ChatProvider>,
);
await waitFor(() => expect(asFragment()).toMatchSnapshot());
});
it('should render provided loading indicator if channels query is in progress', async () => {
const childrenContent = 'Channel children';
const loadingText = 'Loading channels';
render(
<ChatProvider
value={{
channelsQueryState: {
error: null,
queryInProgress: 'reload',
setError: jest.fn(),
setQueryInProgress: jest.fn(),
},
}}
>
<Channel LoadingIndicator={() => <div>{loadingText}</div>}>{childrenContent}</Channel>
</ChatProvider>,
);
await waitFor(() => expect(screen.getByText(loadingText)).toBeInTheDocument());
});
it('should render provided error indicator if channels query failed', async () => {
const childrenContent = 'Channel children';
const errMsg = 'Channels query failed';
render(
<ChatProvider
value={{
channelsQueryState: {
error: new Error(errMsg),
queryInProgress: null,
setError: jest.fn(),
setQueryInProgress: jest.fn(),
},
}}
>
<Channel LoadingErrorIndicator={({ error }) => <div>{error.message}</div>}>
{childrenContent}
</Channel>
</ChatProvider>,
);
await waitFor(() => expect(screen.getByText(errMsg)).toBeInTheDocument());
});
it('should watch the current channel on mount', async () => {
const { channel, chatClient } = await initClient();
const watchSpy = jest.spyOn(channel, 'watch');
await renderComponent({ channel, chatClient });
await waitFor(() => {
expect(watchSpy).toHaveBeenCalledTimes(1);
expect(watchSpy).toHaveBeenCalledWith({ messages: { limit: 25 } });
});
});
it('should apply channelQueryOptions to channel watch call', async () => {
const { channel, chatClient } = await initClient();
const watchSpy = jest.spyOn(channel, 'watch');
const channelQueryOptions = {
messages: { limit: 20 },
};
await renderComponent({ channel, channelQueryOptions, chatClient });
await waitFor(() => {
expect(watchSpy).toHaveBeenCalledTimes(1);
expect(watchSpy).toHaveBeenCalledWith(channelQueryOptions);
});
});
it('should set hasMore state to false if the initial channel query returns less messages than the default initial page size', async () => {
const { channel, chatClient } = await initClient();
useMockedApis(chatClient, [queryChannelWithNewMessages([generateMessage()], channel)]);
let hasMore;
await renderComponent({ channel, chatClient }, ({ hasMore: contextHasMore }) => {
hasMore = contextHasMore;
});
await waitFor(() => {
expect(hasMore).toBe(false);
});
});
// this will only happen if we:
// load with channel A
// switch to channel B and paginate (loadMore - older)
// switch back to channel A (reset hasMore)
// switch back to channel B - messages are already cached and there's more than page size amount
it('should set hasMore state to true if the initial channel query returns more messages than the default initial page size', async () => {
const { channel, chatClient } = await initClient();
useMockedApis(chatClient, [
queryChannelWithNewMessages(Array.from({ length: 26 }, generateMessage), channel),
]);
let hasMore;
await act(() => {
renderComponent({ channel, chatClient }, ({ hasMore: contextHasMore }) => {
hasMore = contextHasMore;
});
});
await waitFor(() => {
expect(hasMore).toBe(true);
});
});
it('should set hasMore state to true if the initial channel query returns count of messages equal to the default initial page size', async () => {
const { channel, chatClient } = await initClient();
useMockedApis(chatClient, [
queryChannelWithNewMessages(Array.from({ length: 25 }, generateMessage), channel),
]);
let hasMore;
await renderComponent({ channel, chatClient }, ({ hasMore: contextHasMore }) => {
hasMore = contextHasMore;
});
await waitFor(() => {
expect(hasMore).toBe(true);
});
});
it('should set hasMore state to false if the initial channel query returns less messages than the custom query channels options message limit', async () => {
const { channel, chatClient } = await initClient();
useMockedApis(chatClient, [queryChannelWithNewMessages([generateMessage()], channel)]);
let hasMore;
const channelQueryOptions = {
messages: { limit: 10 },
};
await renderComponent(
{ channel, channelQueryOptions, chatClient },
({ hasMore: contextHasMore }) => {
hasMore = contextHasMore;
},
);
await waitFor(() => {
expect(hasMore).toBe(false);
});
});
it('should set hasMore state to true if the initial channel query returns count of messages equal custom query channels options message limit', async () => {
const { channel, chatClient } = await initClient();
const equalCount = 10;
useMockedApis(chatClient, [
queryChannelWithNewMessages(Array.from({ length: equalCount }, generateMessage), channel),
]);
let hasMore;
const channelQueryOptions = {
messages: { limit: equalCount },
};
await renderComponent(
{ channel, channelQueryOptions, chatClient },
({ hasMore: contextHasMore }) => {
hasMore = contextHasMore;
},
);
await waitFor(() => {
expect(hasMore).toBe(true);
});
});
it('should not call watch the current channel on mount if channel is initialized', async () => {
const { channel, chatClient } = await initClient();
const watchSpy = jest.spyOn(channel, 'watch');
channel.initialized = true;
await renderComponent({ channel, chatClient });
await waitFor(() => expect(watchSpy).not.toHaveBeenCalled());
});
it('should set an error if watching the channel goes wrong, and render a LoadingErrorIndicator', async () => {
const { channel, chatClient } = await initClient();
const watchError = new Error('watching went wrong');
jest.spyOn(channel, 'watch').mockImplementationOnce(() => Promise.reject(watchError));
await renderComponent({ channel, chatClient });
await waitFor(() =>
expect(LoadingErrorIndicator).toHaveBeenCalledWith(
expect.objectContaining({
error: watchError,
}),
expect.any(Object),
),
);
});
it('should render a LoadingIndicator if it is loading', async () => {
const { channel, chatClient } = await initClient();
const watchPromise = new Promise(() => {});
jest.spyOn(channel, 'watch').mockImplementationOnce(() => watchPromise);
const result = await renderComponent({ channel, chatClient });
await waitFor(() => expect(result.asFragment()).toMatchSnapshot());
});
it('should provide context and render children if channel is set and the component is not loading or errored', async () => {
const { channel, chatClient } = await initClient();
const { findByText } = await renderComponent({
channel,
chatClient,
children: <div>children</div>,
});
expect(await findByText('children')).toBeInTheDocument();
});
it('should store pinned messages as an array in the channel context', async () => {
const { channel, chatClient } = await initClient();
let ctxPins;
const { getByText } = await renderComponent(
{
channel,
chatClient,
children: <div>children</div>,
},
(ctx) => {
ctxPins = ctx.pinnedMessages;
},
);
await waitFor(() => {
expect(getByText('children')).toBeInTheDocument();
expect(Array.isArray(ctxPins)).toBe(true);
});
});
// should these 'on' tests actually test if the handler works?
it('should add a connection recovery handler on the client on mount', async () => {
const { channel, chatClient } = await initClient();
const clientOnSpy = jest.spyOn(chatClient, 'on');
await renderComponent({ channel, chatClient });
await waitFor(() =>
expect(clientOnSpy).toHaveBeenCalledWith('connection.recovered', expect.any(Function)),
);
});
it('should add an `on` handler to the channel on mount', async () => {
const { channel, chatClient } = await initClient();
const channelOnSpy = jest.spyOn(channel, 'on');
await renderComponent({ channel, chatClient });
await waitFor(() => expect(channelOnSpy).toHaveBeenCalledWith(expect.any(Function)));
});
it('should mark the channel as read when the channel is mounted', async () => {
const { channel, chatClient } = await initClient();
jest.spyOn(channel, 'countUnread').mockImplementationOnce(() => 1);
const markReadSpy = jest.spyOn(channel, 'markRead');
await renderComponent({ channel, chatClient });
await waitFor(() => expect(markReadSpy).toHaveBeenCalledWith());
});
it('should not mark the channel as read if the count of unread messages is higher than 0 on mount and the feature is disabled', async () => {
const { channel, chatClient } = await initClient();
jest.spyOn(channel, 'countUnread').mockImplementationOnce(() => 1);
const markReadSpy = jest.spyOn(channel, 'markRead');
await renderComponent({ channel, chatClient, markReadOnMount: false });
await waitFor(() => expect(markReadSpy).not.toHaveBeenCalledWith());
});
it('should use the doMarkReadRequest prop to mark channel as read, if that is defined', async () => {
const { channel, chatClient } = await initClient();
jest.spyOn(channel, 'countUnread').mockImplementationOnce(() => 1);
const doMarkReadRequest = jest.fn();
await renderComponent({
channel,
chatClient,
doMarkReadRequest,
markReadOnMount: true,
});
await waitFor(() => expect(doMarkReadRequest).toHaveBeenCalledTimes(1));
});
it('should not query the channel from the backend when initializeOnMount is disabled', async () => {
const { channel, chatClient } = await initClient();
const watchSpy = jest.spyOn(channel, 'watch').mockImplementationOnce();
await renderComponent({
channel,
chatClient,
initializeOnMount: false,
});
await waitFor(() => expect(watchSpy).not.toHaveBeenCalled());
});
it('should query the channel from the backend when initializeOnMount is enabled (the default)', async () => {
const { channel, chatClient } = await initClient();
const watchSpy = jest.spyOn(channel, 'watch').mockImplementationOnce();
await renderComponent({ channel, chatClient });
await waitFor(() => expect(watchSpy).toHaveBeenCalledTimes(1));
});
describe('Children that consume the contexts set in Channel', () => {
it('should be able to open threads', async () => {
const { channel, chatClient } = await initClient();
const threadMessage = messages[0];
const hasThread = jest.fn();
// this renders Channel, calls openThread from a child context consumer with a message,
// and then calls hasThread with the thread id if it was set.
await renderComponent({ channel, chatClient }, ({ openThread, thread }) => {
if (!thread) {
openThread(threadMessage, { preventDefault: () => null });
} else {
hasThread(thread.id);
}
});
await waitFor(() => expect(hasThread).toHaveBeenCalledWith(threadMessage.id));
});
it('should be able to load more messages in a thread', async () => {
const { channel, chatClient } = await initClient();
const getRepliesSpy = jest.spyOn(channel, 'getReplies');
const threadMessage = messages[0];
const replies = [generateMessage({ parent_id: threadMessage.id })];
useMockedApis(chatClient, [threadRepliesApi(replies)]);
const hasThreadMessages = jest.fn();
await renderComponent(
{ channel, chatClient },
({ loadMoreThread, openThread, thread, threadMessages }) => {
if (!thread) {
// first, open a thread
openThread(threadMessage, { preventDefault: () => null });
} else if (!threadMessages.length) {
// then, load more messages in the thread
loadMoreThread();
} else {
// then, call our mock fn so we can verify what was passed as threadMessages
hasThreadMessages(threadMessages);
}
},
);
await waitFor(() => {
expect(getRepliesSpy).toHaveBeenCalledWith(threadMessage.id, expect.any(Object));
});
await waitFor(() => {
expect(hasThreadMessages).toHaveBeenCalledWith(replies);
});
});
it('should allow closing a thread after it has been opened', async () => {
const { channel, chatClient } = await initClient();
let threadHasClosed = false;
const threadMessage = messages[0];
let threadHasAlreadyBeenOpened = false;
await renderComponent({ channel, chatClient }, ({ closeThread, openThread, thread }) => {
if (!thread) {
// if there is no open thread
if (!threadHasAlreadyBeenOpened) {
// and we haven't opened one before, open a thread
openThread(threadMessage, { preventDefault: () => null });
threadHasAlreadyBeenOpened = true;
} else {
// if we opened it ourselves before, it means the thread was successfully closed
threadHasClosed = true;
}
} else {
// if a thread is open, close it.
closeThread({ preventDefault: () => null });
}
});
await waitFor(() => expect(threadHasClosed).toBe(true));
});
it('should call the onMentionsHover/onMentionsClick prop if a child component calls onMentionsHover with the right event', async () => {
const { channel, chatClient } = await initClient();
const onMentionsHoverMock = jest.fn();
const onMentionsClickMock = jest.fn();
const username = 'Mentioned User';
const mentionedUserMock = {
name: username,
};
const MentionedUserComponent = () => {
const { onMentionsHover } = useChannelActionContext();
return (
<span
onClick={(e) => onMentionsHover(e, [mentionedUserMock])}
onMouseOver={(e) => onMentionsHover(e, [mentionedUserMock])}
>
<strong>@{username}</strong> this is a message
</span>
);
};
const { findByText } = await renderComponent({
channel,
chatClient,
children: <MentionedUserComponent />,
onMentionsClick: onMentionsClickMock,
onMentionsHover: onMentionsHoverMock,
});
const usernameText = await findByText(`@${username}`);
act(() => {
fireEvent.mouseOver(usernameText);
fireEvent.click(usernameText);
});
await waitFor(() =>
expect(onMentionsHoverMock).toHaveBeenCalledWith(
expect.any(Object), // event
mentionedUserMock,
),
);
await waitFor(() =>
expect(onMentionsClickMock).toHaveBeenCalledWith(
expect.any(Object), // event
mentionedUserMock,
),
);
});
describe('loading more messages', () => {
const limit = 10;
it('should be able to load more messages', async () => {
const { channel, chatClient } = await initClient();
const channelQuerySpy = jest.spyOn(channel, 'query');
let newMessageAdded = false;
const newMessages = [generateMessage()];
await renderComponent(
{ channel, chatClient },
({ loadMore, messages: contextMessages }) => {
if (!contextMessages.find((message) => message.id === newMessages[0].id)) {
// Our new message is not yet passed as part of channel context. Call loadMore and mock API response to include it.
useMockedApis(chatClient, [queryChannelWithNewMessages(newMessages, channel)]);
loadMore(limit);
} else {
// If message has been added, update checker so we can verify it happened.
newMessageAdded = true;
}
},
);
await waitFor(() =>
expect(channelQuerySpy).toHaveBeenCalledWith({
messages: {
id_lt: messages[0].id,
limit,
},
watchers: {
limit,
},
}),
);
await waitFor(() => expect(newMessageAdded).toBe(true));
});
it('should set hasMore to false if querying channel returns less messages than the limit', async () => {
const { channel, chatClient } = await initClient();
let channelHasMore = false;
const newMessages = [generateMessage()];
await renderComponent(
{ channel, chatClient },
({ hasMore, loadMore, messages: contextMessages }) => {
if (!contextMessages.find((message) => message.id === newMessages[0].id)) {
// Our new message is not yet passed as part of channel context. Call loadMore and mock API response to include it.
useMockedApis(chatClient, [queryChannelWithNewMessages(newMessages, channel)]);
loadMore(limit);
} else {
// If message has been added, set our checker variable, so we can verify if hasMore is false.
channelHasMore = hasMore;
}
},
);
await waitFor(() => expect(channelHasMore).toBe(false));
});
it('should set hasMore to true if querying channel returns an amount of messages that equals the limit', async () => {
const { channel, chatClient } = await initClient();
let channelHasMore = false;
const newMessages = Array(limit)
.fill(null)
.map(() => generateMessage());
await renderComponent(
{ channel, chatClient },
({ hasMore, loadMore, messages: contextMessages }) => {
if (!contextMessages.some((message) => message.id === newMessages[0].id)) {
// Our new messages are not yet passed as part of channel context. Call loadMore and mock API response to include it.
useMockedApis(chatClient, [queryChannelWithNewMessages(newMessages, channel)]);
loadMore(limit);
} else {
// If message has been added, set our checker variable so we can verify if hasMore is true.
channelHasMore = hasMore;
}
},
);
await waitFor(() => expect(channelHasMore).toBe(true));
});
it('should set loadingMore to true while loading more', async () => {
const { channel, chatClient } = await initClient();
const queryPromise = new Promise(() => {});
let isLoadingMore = false;
await renderComponent({ channel, chatClient }, ({ loadingMore, loadMore }) => {
// return a promise that hasn't resolved yet, so loadMore will be stuck in the 'await' part of the function
jest.spyOn(channel, 'query').mockImplementationOnce(() => queryPromise);
loadMore();
isLoadingMore = loadingMore;
});
await waitFor(() => expect(isLoadingMore).toBe(true));
});
it('should not load the second page, if the previous query has returned less then default limit messages', async () => {
const { channel, chatClient } = await initClient();
const firstPageOfMessages = [generateMessage()];
useMockedApis(chatClient, [queryChannelWithNewMessages(firstPageOfMessages, channel)]);
let queryNextPageSpy;
let contextMessageCount;
await renderComponent(
{ channel, chatClient },
({ loadMore, messages: contextMessages }) => {
queryNextPageSpy = jest.spyOn(channel, 'query');
contextMessageCount = contextMessages.length;
loadMore();
},
);
await waitFor(() => {
expect(queryNextPageSpy).not.toHaveBeenCalled();
expect(chatClient.axiosInstance.post).toHaveBeenCalledTimes(1);
expect(chatClient.axiosInstance.post.mock.calls[0][1]).toMatchObject(
expect.objectContaining({ data: {}, presence: false, state: true, watch: false }),
);
expect(contextMessageCount).toBe(firstPageOfMessages.length);
});
});
it('should load the second page, if the previous query has returned message count equal default messages limit', async () => {
const { channel, chatClient } = await initClient();
const firstPageMessages = Array.from({ length: 25 }, generateMessage);
const secondPageMessages = Array.from({ length: 15 }, generateMessage);
useMockedApis(chatClient, [queryChannelWithNewMessages(firstPageMessages, channel)]);
let queryNextPageSpy;
let contextMessageCount;
await renderComponent(
{ channel, chatClient },
({ loadMore, messages: contextMessages }) => {
queryNextPageSpy = jest.spyOn(channel, 'query');
contextMessageCount = contextMessages.length;
useMockedApis(chatClient, [queryChannelWithNewMessages(secondPageMessages, channel)]);
loadMore();
},
);
await waitFor(() => {
expect(queryNextPageSpy).toHaveBeenCalledTimes(1);
expect(chatClient.axiosInstance.post).toHaveBeenCalledTimes(2);
expect(chatClient.axiosInstance.post.mock.calls[0][1]).toMatchObject({
data: {},
presence: false,
state: true,
watch: false,
});
expect(chatClient.axiosInstance.post.mock.calls[1][1]).toMatchObject(
expect.objectContaining({
data: {},
messages: { id_lt: firstPageMessages[0].id, limit: 100 },
state: true,
watchers: { limit: 100 },
}),
);
expect(contextMessageCount).toBe(firstPageMessages.length + secondPageMessages.length);
});
});
it('should not load the second page, if the previous query has returned less then custom limit messages', async () => {
const { channel, chatClient } = await initClient();
const channelQueryOptions = {
messages: { limit: 10 },
};
const firstPageOfMessages = [generateMessage()];
useMockedApis(chatClient, [queryChannelWithNewMessages(firstPageOfMessages, channel)]);
let queryNextPageSpy;
let contextMessageCount;
await renderComponent(
{ channel, channelQueryOptions, chatClient },
({ loadMore, messages: contextMessages }) => {
queryNextPageSpy = jest.spyOn(channel, 'query');
contextMessageCount = contextMessages.length;
loadMore(channelQueryOptions.messages.limit);
},
);
await waitFor(() => {
expect(queryNextPageSpy).not.toHaveBeenCalled();
expect(chatClient.axiosInstance.post).toHaveBeenCalledTimes(1);
expect(chatClient.axiosInstance.post.mock.calls[0][1]).toMatchObject({
data: {},
messages: {
limit: channelQueryOptions.messages.limit,
},
presence: false,
state: true,
watch: false,
});
expect(contextMessageCount).toBe(firstPageOfMessages.length);
});
});
it('should load the second page, if the previous query has returned message count equal custom messages limit', async () => {
const { channel, chatClient } = await initClient();
const equalCount = 10;
const channelQueryOptions = {
messages: { limit: equalCount },
};
const firstPageMessages = Array.from({ length: equalCount }, generateMessage);
const secondPageMessages = Array.from({ length: equalCount - 1 }, generateMessage);
useMockedApis(chatClient, [queryChannelWithNewMessages(firstPageMessages, channel)]);
let queryNextPageSpy;
let contextMessageCount;
await renderComponent(
{ channel, channelQueryOptions, chatClient },
({ loadMore, messages: contextMessages }) => {
queryNextPageSpy = jest.spyOn(channel, 'query');
contextMessageCount = contextMessages.length;
useMockedApis(chatClient, [queryChannelWithNewMessages(secondPageMessages, channel)]);
loadMore(channelQueryOptions.messages.limit);
},
);
await waitFor(() => {
expect(queryNextPageSpy).toHaveBeenCalledTimes(1);
expect(chatClient.axiosInstance.post).toHaveBeenCalledTimes(2);
expect(chatClient.axiosInstance.post.mock.calls[0][1]).toMatchObject({
data: {},
messages: {
limit: channelQueryOptions.messages.limit,
},
presence: false,
state: true,
watch: false,
});
expect(chatClient.axiosInstance.post.mock.calls[1][1]).toMatchObject(
expect.objectContaining({
data: {},
messages: {
id_lt: firstPageMessages[0].id,
limit: channelQueryOptions.messages.limit,
},
state: true,
watchers: { limit: channelQueryOptions.messages.limit },
}),
);
expect(contextMessageCount).toBe(firstPageMessages.length + secondPageMessages.length);
});
});
});
describe('jump to first unread message', () => {
const defaultQueryLimit = 100;
const user = generateUser();
const last_read_message_id = 'X';
const errorNotificationText = 'Failed to jump to the first unread message';
afterEach(jest.resetAllMocks);
it('should not query messages around the last read message if the unread count is falsy', async () => {
const {
channels: [channel],
client: chatClient,
} = await initClientWithChannels({
channelsData: [
{
messages: [generateMessage()],
read: [{ last_read: new Date().toISOString(), user }],
unread_messages: 0,
},
],
customUser: user,
});
const loadMessageIntoState = jest
.spyOn(channel.state, 'loadMessageIntoState')
.mockImplementation();
let hasJumped;
await renderComponent({ channel, chatClient }, ({ jumpToFirstUnreadMessage }) => {
if (hasJumped) {
return;
}
jumpToFirstUnreadMessage();
hasJumped = true;
});
await waitFor(() => {
expect(loadMessageIntoState).not.toHaveBeenCalled();
});
});
it('should not query messages around the last read message if the last read message is unknown', async () => {
const {
channels: [channel],
client: chatClient,
} = await initClientWithChannels({
channelsData: [
{
messages: [generateMessage()],
read: [{ last_read: new Date().toISOString(), unread_messages: 1, user }],
},
],
customUser: user,
});
const loadMessageIntoState = jest
.spyOn(channel.state, 'loadMessageIntoState')
.mockImplementation();
let hasJumped;
let notifications;
await renderComponent(
{ channel, chatClient },
({
channelUnreadUiState,
jumpToFirstUnreadMessage,
notifications: contextNotifications,
}) => {
if (hasJumped || !channelUnreadUiState) {
notifications = contextNotifications;
return;
}
jumpToFirstUnreadMessage();
hasJumped = true;
},
);
await waitFor(() => {
expect(loadMessageIntoState).not.toHaveBeenCalled();
expect(notifications).toHaveLength(1);
expect(notifications[0].text).toBe(errorNotificationText);
});
});
it('should not query messages around the last read message if the last read message is unknown and show error notification', async () => {
const {
channels: [channel],
client: chatClient,
} = await initClientWithChannels({
channelsData: [
{