-
Notifications
You must be signed in to change notification settings - Fork 373
Expand file tree
/
Copy pathChannel.test.js
More file actions
629 lines (523 loc) · 19.4 KB
/
Channel.test.js
File metadata and controls
629 lines (523 loc) · 19.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
import React, { useContext, useEffect } from 'react';
import { View } from 'react-native';
import { act, cleanup, render, renderHook, waitFor } from '@testing-library/react-native';
import { StreamChat } from 'stream-chat';
import { ChannelContext, ChannelProvider } from '../../../contexts/channelContext/ChannelContext';
import { ChannelsStateProvider } from '../../../contexts/channelsStateContext/ChannelsStateContext';
import {
MessagesContext,
MessagesProvider,
} from '../../../contexts/messagesContext/MessagesContext';
import { ThreadContext, ThreadProvider } from '../../../contexts/threadContext/ThreadContext';
import { getOrCreateChannelApi } from '../../../mock-builders/api/getOrCreateChannel';
import { useMockedApis } from '../../../mock-builders/api/useMockedApis';
import dispatchConnectionChanged from '../../../mock-builders/event/connectionChanged';
import { generateChannelResponse } from '../../../mock-builders/generator/channel';
import { generateMember } from '../../../mock-builders/generator/member';
import { generateMessage } from '../../../mock-builders/generator/message';
import { generateUser } from '../../../mock-builders/generator/user';
import { getTestClientWithUser } from '../../../mock-builders/mock';
import { Attachment } from '../../Attachment/Attachment';
import { Chat } from '../../Chat/Chat';
import { Channel } from '../Channel';
import {
channelInitialState,
useChannelDataState,
useChannelMessageDataState,
} from '../hooks/useChannelDataState';
import * as MessageListPaginationHooks from '../hooks/useMessageListPagination';
// This component is used for performing effects in a component that consumes ChannelContext,
// i.e. making use of the callbacks & values provided by the Channel component.
// the effect is called every time channelContext changes
const CallbackEffectWithContext = ({ callback, context }) => {
const ctx = useContext(context);
useEffect(() => {
callback(ctx);
}, [callback, ctx]);
return <View />;
};
const ContextConsumer = ({ context, fn }) => {
fn(useContext(context));
return <View testID='children' />;
};
let chatClient;
let channel;
const user = generateUser({ id: 'id', name: 'name' });
const messages = [generateMessage({ user })];
const renderComponent = (props = {}, callback = () => {}, context = ChannelContext) =>
render(
<ChannelsStateProvider>
<Chat client={chatClient}>
<Channel {...props}>
{props.children}
<CallbackEffectWithContext {...{ callback, context }} />
</Channel>
</Chat>
</ChannelsStateProvider>,
);
describe('Channel', () => {
beforeEach(async () => {
const members = [generateMember({ user })];
const mockedChannel = generateChannelResponse({
members,
messages,
});
chatClient = await getTestClientWithUser(user);
useMockedApis(chatClient, [getOrCreateChannelApi(mockedChannel)]);
channel = chatClient.channel('messaging', mockedChannel.id);
channel.cid = mockedChannel.channel.cid;
});
afterEach(() => {
jest.clearAllMocks();
cleanup();
});
it('should render a simple text error if the channel id does not exist', async () => {
const nullChannel = {
...channel,
cid: null,
countUnread: () => 0,
off: () => {},
on: () => ({
unsubscribe: () => null,
}),
watch: () => {},
};
const { getByTestId } = renderComponent({ channel: nullChannel });
await waitFor(() => {
expect(getByTestId('no-channel')).toBeTruthy();
});
});
it('should watch the current channel on mount', async () => {
const watchSpy = jest.spyOn(channel, 'watch');
renderComponent({ channel });
await waitFor(() => expect(watchSpy).toHaveBeenCalledTimes(1));
});
it('should set an error if channel watch fails and render a LoadingErrorIndicator', async () => {
const watchError = new Error('channel watch fail');
jest.spyOn(channel, 'watch').mockImplementationOnce(() => Promise.reject(watchError));
const { getByTestId } = renderComponent({ channel });
await waitFor(() => expect(getByTestId('loading-error')).toBeTruthy());
});
it('should render children if a channel is set', async () => {
const { getByTestId } = renderComponent({
channel,
children: <View testID='children' />,
});
await waitFor(() => expect(getByTestId('children')).toBeTruthy());
});
it('should add a connection recovery handler to the client on mount', async () => {
const clientOnSpy = jest.spyOn(chatClient, 'on');
renderComponent({ channel });
await waitFor(() =>
expect(clientOnSpy).toHaveBeenCalledWith('connection.recovered', expect.any(Function)),
);
});
it('should add an `on` handler to the channel on mount', async () => {
const channelOnSpy = jest.spyOn(channel, 'on');
renderComponent({ channel });
await waitFor(() => expect(channelOnSpy).toHaveBeenCalledWith(expect.any(Function)));
});
it('should be able to open threads', async () => {
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.
const { rerender } = renderComponent(
{ channel },
({ openThread, thread }) => {
if (!thread) {
openThread(threadMessage);
} else {
hasThread(thread.id);
}
},
ThreadContext,
);
rerender(
<ChannelsStateProvider>
<Chat client={chatClient}>
<Channel channel={channel}>
<CallbackEffectWithContext
callback={({ openThread, thread }) => {
if (!thread) {
openThread(threadMessage);
} else {
hasThread(thread.id);
}
}}
context={ThreadContext}
/>
</Channel>
</Chat>
</ChannelsStateProvider>,
);
await waitFor(() => expect(hasThread).toHaveBeenCalledWith(threadMessage.id));
});
const queryChannelWithNewMessages = (newMessages) =>
// generate new channel mock from existing channel with new messages added
getOrCreateChannelApi(
generateChannelResponse({
channel: {
config: channel.getConfig(),
id: channel.id,
type: channel.type,
},
messages: newMessages,
}),
);
it('should call the channel query method to load more messages', async () => {
const channelQuerySpy = jest.spyOn(channel, 'query');
const newMessages = [generateMessage()];
renderComponent(
{ channel },
() => {
useMockedApis(chatClient, [queryChannelWithNewMessages(newMessages)]);
},
MessagesContext,
);
await waitFor(() => expect(channelQuerySpy).toHaveBeenCalled());
});
describe('ChannelContext', () => {
it('renders children without crashing', async () => {
const { getByTestId } = render(
<ChannelProvider>
<View testID='children' />
</ChannelProvider>,
);
await waitFor(() => expect(getByTestId('children')).toBeTruthy());
});
it('exposes the channel context', async () => {
let context;
const mockContext = {
channel,
client: chatClient,
markRead: () => {},
watcherCount: 5,
};
render(
<ChannelProvider value={mockContext}>
<ContextConsumer
context={ChannelContext}
fn={(ctx) => {
context = ctx;
}}
/>
</ChannelProvider>,
);
await waitFor(() => {
expect(context).toBeInstanceOf(Object);
expect(context.channel).toBeInstanceOf(Object);
expect(context.client).toBeInstanceOf(StreamChat);
expect(context.markRead).toBeInstanceOf(Function);
expect(context.watcherCount).toBe(5);
});
});
});
describe('MessagesContext', () => {
it('renders children without crashing', async () => {
const { getByTestId } = render(
<MessagesProvider>
<View testID='children' />
</MessagesProvider>,
);
await waitFor(() => expect(getByTestId('children')).toBeTruthy());
});
it('exposes the messages context', async () => {
let context;
const mockContext = {
Attachment,
editing: false,
messages,
sendMessage: () => {},
};
render(
<MessagesProvider value={mockContext}>
<ContextConsumer
context={MessagesContext}
fn={(ctx) => {
context = ctx;
}}
/>
</MessagesProvider>,
);
await waitFor(() => {
expect(context).toBeInstanceOf(Object);
expect(context.Attachment).toBeInstanceOf(Function);
expect(context.editing).toBe(false);
expect(context.messages).toBeInstanceOf(Array);
expect(context.sendMessage).toBeInstanceOf(Function);
});
});
});
describe('ThreadContext', () => {
it('renders children without crashing', async () => {
const { getByTestId } = render(
<ThreadProvider>
<View testID='children' />
</ThreadProvider>,
);
await waitFor(() => expect(getByTestId('children')).toBeTruthy());
});
it('exposes the thread context', async () => {
let context;
const mockContext = {
openThread: () => {},
thread: {},
threadHasMore: true,
threadLoadingMore: false,
};
render(
<ThreadProvider value={mockContext}>
<ContextConsumer
context={ThreadContext}
fn={(ctx) => {
context = ctx;
}}
/>
</ThreadProvider>,
);
await waitFor(() => {
expect(context).toBeInstanceOf(Object);
expect(context.openThread).toBeInstanceOf(Function);
expect(context.thread).toBeInstanceOf(Object);
expect(context.threadHasMore).toBe(true);
expect(context.threadLoadingMore).toBe(false);
});
});
});
});
describe('Channel initial load useEffect', () => {
let chatClient;
const renderComponent = (props = {}) =>
render(
<Chat client={chatClient}>
<Channel {...props}>{props.children}</Channel>
</Chat>,
);
beforeEach(async () => {
chatClient = await getTestClientWithUser(user);
});
afterEach(() => {
jest.clearAllMocks();
cleanup();
});
it('should still call channel.watch if we are online and DB channels are loaded', async () => {
const messages = Array.from({ length: 10 }, (_, i) => generateMessage({ id: i }));
const mockedChannel = generateChannelResponse({
messages,
});
useMockedApis(chatClient, [getOrCreateChannelApi(mockedChannel)]);
const channel = chatClient.channel('messaging', mockedChannel.id);
await channel.watch();
channel.offlineMode = true;
channel.state = {
...channelInitialState,
messagePagination: {
hasPrev: true,
},
};
const watchSpy = jest.fn();
channel.watch = watchSpy;
renderComponent({ channel });
await waitFor(() => expect(watchSpy).toHaveBeenCalledTimes(1));
});
it("should call channel.watch if channel is initialized and it's not in offline mode", async () => {
const messages = Array.from({ length: 10 }, (_, i) => generateMessage({ id: i }));
const mockedChannel = generateChannelResponse({
messages,
});
useMockedApis(chatClient, [getOrCreateChannelApi(mockedChannel)]);
const channel = chatClient.channel('messaging', mockedChannel.id);
await channel.watch();
channel.state = {
...channelInitialState,
members: Object.fromEntries(
Array.from({ length: 10 }, (_, i) => [i, generateMember({ id: i })]),
),
messagePagination: {
hasPrev: true,
},
messages: Array.from({ length: 10 }, (_, i) => generateMessage({ id: i })),
};
const watchSpy = jest.fn();
channel.offlineMode = false;
channel.initialied = false;
channel.watch = watchSpy;
renderComponent({ channel });
const { result: channelMessageState } = renderHook(() => useChannelMessageDataState(channel));
const { result: channelState } = renderHook(() => useChannelDataState(channel));
await waitFor(() => expect(watchSpy).toHaveBeenCalled());
await waitFor(() => expect(channelMessageState.current.state.messages).toHaveLength(10));
await waitFor(() => expect(Object.keys(channelState.current.state.members)).toHaveLength(10));
});
function getElementsAround(array, key, id) {
const index = array.findIndex((obj) => obj[key] === id);
if (index === -1) {
return [];
}
const start = Math.max(0, index - 12); // 12 before the index
const end = Math.min(array.length, index + 13); // 12 after the index
return array.slice(start, end);
}
it('should call the loadChannelAroundMessage when messageId is passed to a channel', async () => {
const messages = Array.from({ length: 105 }, (_, i) => generateMessage({ id: i }));
const messageToSearch = messages[50];
const mockedChannel = generateChannelResponse({
messages,
});
useMockedApis(chatClient, [getOrCreateChannelApi(mockedChannel)]);
const channel = chatClient.channel('messaging', mockedChannel.id);
await channel.watch();
const loadMessageIntoState = jest.fn(() => {
const newMessages = getElementsAround(messages, 'id', messageToSearch.id);
channel.state.messages = newMessages;
});
channel.state = {
...channelInitialState,
loadMessageIntoState,
messagePagination: {
hasNext: true,
hasPrev: true,
},
messages,
};
renderComponent({ channel, messageId: messageToSearch.id });
await waitFor(() => {
expect(loadMessageIntoState).toHaveBeenCalledWith(messageToSearch.id, undefined, 25);
});
const { result: channelMessageState } = renderHook(() => useChannelMessageDataState(channel));
await waitFor(() => expect(channelMessageState.current.state.messages).toHaveLength(25));
await waitFor(() =>
expect(
channelMessageState.current.state.messages.find(
(message) => message.id === messageToSearch.id,
),
).toBeTruthy(),
);
});
describe('initialScrollToFirstUnreadMessage', () => {
afterEach(() => {
// Clear all mocks after each test
jest.clearAllMocks();
// Restore all mocks to their original implementation
jest.restoreAllMocks();
cleanup();
});
const mockedHook = (values) =>
jest.spyOn(MessageListPaginationHooks, 'useMessageListPagination').mockImplementation(() => ({
copyMessagesStateFromChannel: jest.fn(),
loadChannelAroundMessage: jest.fn(),
loadChannelAtFirstUnreadMessage: jest.fn(),
loadInitialMessagesStateFromChannel: jest.fn(),
loadLatestMessages: jest.fn(),
loadMore: jest.fn(),
loadMoreRecent: jest.fn(),
state: { ...channelInitialState },
...values,
}));
it("should not call loadChannelAtFirstUnreadMessage if channel's unread count is 0", async () => {
const mockedChannel = generateChannelResponse({
messages: Array.from({ length: 10 }, (_, i) => generateMessage({ text: `message-${i}` })),
});
useMockedApis(chatClient, [getOrCreateChannelApi(mockedChannel)]);
const channel = chatClient.channel('messaging', mockedChannel.id);
await channel.watch();
const user = generateUser();
const read_data = {};
read_data[chatClient.user.id] = {
last_read: new Date(),
user,
};
channel.state = {
...channelInitialState,
read: read_data,
};
jest.spyOn(channel, 'countUnread').mockImplementation(() => 0);
const loadChannelAtFirstUnreadMessageFn = jest.fn();
mockedHook({ loadChannelAtFirstUnreadMessage: loadChannelAtFirstUnreadMessageFn });
renderComponent({ channel, initialScrollToFirstUnreadMessage: true });
await waitFor(() => {
expect(loadChannelAtFirstUnreadMessageFn).not.toHaveBeenCalled();
});
});
it("should call loadChannelAtFirstUnreadMessage if channel's unread count is greater than 0", async () => {
const mockedChannel = generateChannelResponse({
messages: Array.from({ length: 10 }, (_, i) => generateMessage({ text: `message-${i}` })),
});
useMockedApis(chatClient, [getOrCreateChannelApi(mockedChannel)]);
const channel = chatClient.channel('messaging', mockedChannel.id);
await channel.watch();
const user = generateUser();
const numberOfUnreadMessages = 15;
const read_data = {};
read_data[chatClient.user.id] = {
last_read: new Date(),
unread_messages: numberOfUnreadMessages,
user,
};
channel.state = {
...channelInitialState,
read: read_data,
};
jest.spyOn(channel, 'countUnread').mockImplementation(() => numberOfUnreadMessages);
const loadChannelAtFirstUnreadMessageFn = jest.fn();
mockedHook({ loadChannelAtFirstUnreadMessage: loadChannelAtFirstUnreadMessageFn });
renderComponent({ channel, initialScrollToFirstUnreadMessage: true });
await waitFor(() => {
expect(loadChannelAtFirstUnreadMessageFn).toHaveBeenCalled();
});
});
it("should not call loadChannelAtFirstUnreadMessage if channel's unread count is greater than 0 lesser than scrollToFirstUnreadThreshold", async () => {
const mockedChannel = generateChannelResponse({
messages: Array.from({ length: 10 }, (_, i) => generateMessage({ text: `message-${i}` })),
});
useMockedApis(chatClient, [getOrCreateChannelApi(mockedChannel)]);
const channel = chatClient.channel('messaging', mockedChannel.id);
await channel.watch();
const user = generateUser();
const numberOfUnreadMessages = 2;
const read_data = {};
read_data[chatClient.user.id] = {
last_read: new Date(),
unread_messages: numberOfUnreadMessages,
user,
};
channel.state = {
...channelInitialState,
read: read_data,
};
jest.spyOn(channel, 'countUnread').mockImplementation(() => numberOfUnreadMessages);
const loadChannelAtFirstUnreadMessageFn = jest.fn();
mockedHook({ loadChannelAtFirstUnreadMessage: loadChannelAtFirstUnreadMessageFn });
renderComponent({ channel, initialScrollToFirstUnreadMessage: true });
await waitFor(() => {
expect(loadChannelAtFirstUnreadMessageFn).not.toHaveBeenCalled();
});
});
});
it('should call resyncChannel when connection changed event is triggered', async () => {
const mockedChannel = generateChannelResponse({
messages: Array.from({ length: 10 }, (_, i) => generateMessage({ text: `message-${i}` })),
});
useMockedApis(chatClient, [getOrCreateChannelApi(mockedChannel)]);
const channel = chatClient.channel('messaging', mockedChannel.id);
await channel.watch();
renderComponent({ channel });
await waitFor(() => {
act(() => dispatchConnectionChanged(chatClient, false));
});
await waitFor(() => {
channel.state.addMessagesSorted(
Array.from({ length: 10 }, (_, i) =>
generateMessage({ status: 'failed', text: `message-${i}` }),
),
);
});
await waitFor(() => {
act(() => dispatchConnectionChanged(chatClient));
});
await waitFor(() => {
expect(channel.state.messages.length).toBe(20);
});
});
});