-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathStatefulChatClient.test.ts
More file actions
449 lines (370 loc) · 16.3 KB
/
StatefulChatClient.test.ts
File metadata and controls
449 lines (370 loc) · 16.3 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { ChatThreadItem } from '@azure/communication-chat';
import { PagedAsyncIterableIterator } from '@azure/core-paging';
import {
ChatMessageDeletedEvent,
ChatMessageEditedEvent,
ChatMessageReceivedEvent,
ChatParticipant,
ChatThreadCreatedEvent,
ChatThreadDeletedEvent,
ChatThreadPropertiesUpdatedEvent,
ParticipantsAddedEvent,
ParticipantsRemovedEvent,
ReadReceiptReceivedEvent,
TypingIndicatorReceivedEvent
} from '@azure/communication-signaling';
import { createStatefulChatClientWithDeps } from './StatefulChatClient';
import { ChatClientState, ChatError } from './ChatClientState';
import { Constants } from './Constants';
import {
StateChangeListener,
StatefulChatClientWithEventTrigger,
createMockChatClient,
createStatefulChatClientMock,
defaultClientArgs,
failingPagedAsyncIterator,
mockChatThreads
} from './TestHelpers';
jest.useFakeTimers();
const mockParticipants: ChatParticipant[] = [
{ id: { kind: 'communicationUser', communicationUserId: 'user1' }, displayName: 'user1' },
{ id: { kind: 'communicationUser', communicationUserId: 'user2' }, displayName: 'user1' }
];
describe('declarative chatThread list iterators', () => {
test('declarative listChatThreads should proxy listChatThreads iterator and store it in internal state', async () => {
const client = createStatefulChatClientMock();
const chatThreads = client.listChatThreads();
const proxiedThreads: ChatThreadItem[] = [];
for await (const thread of chatThreads) {
proxiedThreads.push(thread);
}
expect(proxiedThreads.length).toBe(mockChatThreads.length);
expect(Object.keys(client.getState().threads).length).toBe(mockChatThreads.length);
});
test('declarative listChatThreads should proxy listChatThreads paged iterator and store it in internal state', async () => {
const client = createStatefulChatClientMock();
const pages = client.listChatThreads().byPage();
const proxiedThreads: ChatThreadItem[] = [];
for await (const page of pages) {
for (const thread of page) {
proxiedThreads.push(thread);
}
}
expect(proxiedThreads.length).toBe(mockChatThreads.length);
expect(Object.keys(client.getState().threads).length).toBe(mockChatThreads.length);
});
});
describe('declarative chatClient basic api functions', () => {
test('set internal store correctly when proxy getChatThreadClient and deleteThread', async () => {
const client = createStatefulChatClientMock();
await client.getChatThreadClient(mockChatThreads[0].id);
expect(Object.keys(client.getState().threads).length).toBe(1);
expect(client.getState().threads[mockChatThreads[0].id]).toBeDefined();
await client.deleteChatThread(mockChatThreads[0].id);
expect(Object.keys(client.getState().threads).length).toBe(0);
});
test('set internal store correctly when proxy createChatThread', async () => {
const client = createStatefulChatClientMock();
const topic = 'topic';
const response = await client.createChatThread({ topic });
const threadId = response.chatThread?.id ?? '';
expect(Object.keys(client.getState().threads).length).toBe(1);
const thread = client.getState().threads[threadId];
expect(thread).toBeDefined();
expect(thread?.properties?.topic).toBe(topic);
});
test('declaratify chatThreadClient when return getChatThreadClient', async () => {
const client = createStatefulChatClientMock();
const threadId = 'threadId';
const chatThreadClient = client.getChatThreadClient(threadId);
expect(client.getState().threads[threadId]).toBeDefined();
await chatThreadClient.sendMessage({ content: 'test' });
expect(Object.values(client.getState().threads[threadId]?.chatMessages ?? {}).length).toBe(1);
});
});
describe('declarative chatClient subscribe to event properly after startRealtimeNotification', () => {
let client: StatefulChatClientWithEventTrigger;
beforeEach(() => {
client = createStatefulChatClientMock();
client.startRealtimeNotifications();
});
afterEach(() => {
client.stopRealtimeNotifications();
});
test('set internal store correctly when receive thread related event', async () => {
const threadId = 'threadId1';
const topic = 'topic';
const event: ChatThreadCreatedEvent = {
threadId,
version: '',
properties: { topic },
createdOn: new Date('01-01-2020'),
createdBy: { id: { kind: 'communicationUser', communicationUserId: 'user1' }, displayName: '' },
participants: mockParticipants
};
await client.triggerEvent('chatThreadCreated', event);
expect(client.getState().threads[threadId]).toBeDefined();
expect(client.getState().threads[threadId]?.properties?.topic).toBe(topic);
// edit event
const editedTopic = 'new topic';
const editEvent: ChatThreadPropertiesUpdatedEvent = {
...event,
properties: { topic: editedTopic },
updatedBy: { displayName: '', id: { kind: 'communicationUser', communicationUserId: 'user1' } },
updatedOn: new Date('01-01-2020')
};
await client.triggerEvent('chatThreadPropertiesUpdated', editEvent);
expect(client.getState().threads[threadId]?.properties?.topic).toBe(editedTopic);
// delete event
const deletedEvent: ChatThreadDeletedEvent = {
...event,
deletedBy: { displayName: '', id: { kind: 'communicationUser', communicationUserId: 'user1' } },
deletedOn: new Date('01-01-2020')
};
await client.triggerEvent('chatThreadDeleted', deletedEvent);
expect(Object.keys(client.getState().threads).length).toBe(0);
});
test('set internal store correctly when receive chatMessage related events', async () => {
const threadId = 'threadId1';
const messageId = 'messageId1';
const event: ChatMessageReceivedEvent = {
threadId,
id: messageId,
type: 'text',
version: '',
createdOn: new Date('01-01-2020'),
sender: { kind: 'communicationUser', communicationUserId: 'sender1' },
senderDisplayName: '',
message: 'message',
recipient: { kind: 'communicationUser', communicationUserId: 'userId1' },
metadata: {}
};
await client.triggerEvent('chatMessageReceived', event);
expect(client.getState().threads[threadId]?.chatMessages[messageId]).toBeDefined();
// edit event
const message = 'editedContent';
const editedEvent: ChatMessageEditedEvent = {
...event,
message: message,
editedOn: new Date('01-01-2020')
};
await client.triggerEvent('chatMessageEdited', editedEvent);
expect(client.getState().threads[threadId]?.chatMessages[messageId]?.content?.message).toBe(message);
// delete event
const deleteEvent: ChatMessageDeletedEvent = {
...event,
deletedOn: new Date('01-01-2020')
};
await client.triggerEvent('chatMessageDeleted', deleteEvent);
expect(Object.values(client.getState().threads[threadId]?.chatMessages ?? {}).length).toBe(0);
});
test('set internal store correctly when receive participant related events', async () => {
const threadId = 'threadId1';
const addedEvent: ParticipantsAddedEvent = {
threadId,
addedBy: { id: { kind: 'communicationUser', communicationUserId: 'user1' }, displayName: '' },
addedOn: new Date('01-01-2020'),
participantsAdded: mockParticipants,
version: ''
};
await client.triggerEvent('participantsAdded', addedEvent);
expect(Object.keys(client.getState().threads[threadId]?.participants ?? {}).length).toBe(2);
// remove event
const removedEvent: ParticipantsRemovedEvent = {
threadId,
participantsRemoved: [mockParticipants[0]],
version: '',
removedBy: { id: { kind: 'communicationUser', communicationUserId: 'user1' }, displayName: '' },
removedOn: new Date('01-01-2020')
};
await client.triggerEvent('participantsRemoved', removedEvent);
expect(Object.keys(client.getState().threads[threadId]?.participants ?? {}).length).toBe(1);
});
test('set internal store correctly when receive typingIndicator events', async () => {
const threadId = 'threadId1';
const addedEvent: TypingIndicatorReceivedEvent = {
threadId,
receivedOn: new Date(),
recipient: { kind: 'communicationUser', communicationUserId: 'user2' },
sender: { kind: 'communicationUser', communicationUserId: 'user3' },
senderDisplayName: '',
version: ''
};
await client.triggerEvent('typingIndicatorReceived', addedEvent);
await client.triggerEvent('typingIndicatorReceived', addedEvent);
expect(client.getState().threads[threadId]?.typingIndicators.length).toBe(2);
});
test('only maintain recent 30s typingIndicator', async () => {
const threadId = 'threadId1';
const addedEvent: TypingIndicatorReceivedEvent = {
threadId,
receivedOn: new Date(Date.now() - (Constants.TYPING_INDICATOR_MAINTAIN_TIME + 1 * 1000)),
recipient: { kind: 'communicationUser', communicationUserId: 'user2' },
sender: { kind: 'communicationUser', communicationUserId: 'user3' },
senderDisplayName: '',
version: ''
};
await client.triggerEvent('typingIndicatorReceived', addedEvent);
jest.advanceTimersByTime(1500);
expect(client.getState().threads[threadId]?.typingIndicators.length).toBe(0);
});
test('set internal store correctly when receive readReceiptReceived events', async () => {
const threadId = 'threadId1';
const messageId = 'messageId1';
const readOn = new Date();
const addedEvent: ReadReceiptReceivedEvent = {
threadId,
readOn,
recipient: { kind: 'communicationUser', communicationUserId: 'user1' },
sender: { kind: 'communicationUser', communicationUserId: 'user1' },
senderDisplayName: '',
chatMessageId: 'messageId1'
};
client.triggerEvent('readReceiptReceived', addedEvent);
expect(client.getState().threads[threadId]?.readReceipts.length).toBe(1);
expect(client.getState().threads[threadId]?.readReceipts[0].chatMessageId).toBe(messageId);
expect(client.getState().threads[threadId]?.latestReadTime).toEqual(readOn);
});
});
describe('declarative chatClient unsubscribe', () => {
test('unsubscribe events correctly ', async () => {
const threadId = 'threadId1';
const client = createStatefulChatClientMock();
await client.startRealtimeNotifications();
await client.stopRealtimeNotifications();
const addedEvent: ReadReceiptReceivedEvent = {
threadId,
readOn: new Date('01-01-2020'),
recipient: { kind: 'communicationUser', communicationUserId: 'user1' },
sender: { kind: 'communicationUser', communicationUserId: 'user1' },
senderDisplayName: '',
chatMessageId: 'messageId1'
};
client.triggerEvent('readReceiptReceived', addedEvent);
expect(client.getState().threads[threadId]?.readReceipts).toBe(undefined);
});
});
describe('declarative chatClient onStateChange', () => {
test('will be triggered when state gets updated', async () => {
const client = createStatefulChatClientMock();
let state: ChatClientState = client.getState();
let onChangeCalled = false;
client.onStateChange((_state) => {
state = _state;
onChangeCalled = true;
});
await client.createChatThread({ topic: 'topic' });
expect(onChangeCalled).toBeTruthy();
expect(Object.keys(state.threads).length).toBe(1);
});
test('offStateChange will unsubscribe correctly', async () => {
const client = createStatefulChatClientMock();
let onChangeCalledTimes = 0;
const callback = (): void => {
onChangeCalledTimes++;
};
client.onStateChange(callback);
await client.createChatThread({ topic: 'topic' });
expect(onChangeCalledTimes).toBe(1);
client.offStateChange(callback);
await client.createChatThread({ topic: 'topic' });
expect(onChangeCalledTimes).toBe(1);
});
});
describe('stateful wraps thrown error', () => {
test('when listChatThreads fails immedately', async () => {
const baseClient = createMockChatClient();
baseClient.listChatThreads = (): PagedAsyncIterableIterator<ChatThreadItem> => {
throw Error('injected error');
};
const client = createStatefulChatClientWithDeps(baseClient, defaultClientArgs);
expect(client.listChatThreads).toThrow(new ChatError('ChatClient.listChatThreads', new Error('injected error')));
});
test('when listChatThreads fails while iterating items', async () => {
const baseClient = createMockChatClient();
baseClient.listChatThreads = (): PagedAsyncIterableIterator<ChatThreadItem> => {
return failingPagedAsyncIterator(new Error('injected error'));
};
const client = createStatefulChatClientWithDeps(baseClient, defaultClientArgs);
const iter = client.listChatThreads();
await expect(iter.next()).rejects.toThrow(new ChatError('ChatClient.listChatThreads', new Error('injected error')));
await expect(iter.byPage().next()).rejects.toThrow(
new ChatError('ChatClient.listChatThreads', new Error('injected error'))
);
});
test('when createChatThread fails', async () => {
const baseClient = createMockChatClient();
baseClient.createChatThread = async () => {
throw Error('injected error');
};
const client = createStatefulChatClientWithDeps(baseClient, defaultClientArgs);
await expect(client.createChatThread({ topic: '' })).rejects.toThrow(
new ChatError('ChatClient.createChatThread', new Error('injected error'))
);
});
test('when deleteChatThread fails', async () => {
const baseClient = createMockChatClient();
baseClient.deleteChatThread = async () => {
throw Error('injected error');
};
const client = createStatefulChatClientWithDeps(baseClient, defaultClientArgs);
await expect(client.deleteChatThread('')).rejects.toThrow(
new ChatError('ChatClient.deleteChatThread', new Error('injected error'))
);
});
test('when startRealtimeNotifications fails', async () => {
const baseClient = createMockChatClient();
baseClient.startRealtimeNotifications = async () => {
throw Error('injected error');
};
const client = createStatefulChatClientWithDeps(baseClient, defaultClientArgs);
await expect(client.startRealtimeNotifications()).rejects.toThrow(
new ChatError('ChatClient.startRealtimeNotifications', new Error('injected error'))
);
});
test('when stopRealtimeNotifications fails', async () => {
const baseClient = createMockChatClient();
baseClient.stopRealtimeNotifications = async () => {
throw Error('injected error');
};
const client = createStatefulChatClientWithDeps(baseClient, defaultClientArgs);
await expect(client.stopRealtimeNotifications()).rejects.toThrow(
new ChatError('ChatClient.stopRealtimeNotifications', new Error('injected error'))
);
});
});
describe('stateful chatClient tees errors to state', () => {
test('when startRealtimeNotifications fails', async () => {
const baseClient = createMockChatClient();
baseClient.startRealtimeNotifications = async () => {
throw Error('injected error');
};
const client = createStatefulChatClientWithDeps(baseClient, defaultClientArgs);
const listener = new StateChangeListener(client);
await expect(client.startRealtimeNotifications()).rejects.toThrow();
expect(listener.onChangeCalledCount).toBe(1);
const latestError = listener.state.latestErrors['ChatClient.startRealtimeNotifications'];
expect(latestError).toBeDefined();
});
});
describe('complex error handling for startRealtimeNotifications', () => {
test('latest error is stored in state', async () => {
const baseClient = createMockChatClient();
let errorCount = 0;
baseClient.startRealtimeNotifications = async () => {
errorCount++;
throw Error(`injected error #${errorCount}`);
};
const client = createStatefulChatClientWithDeps(baseClient, defaultClientArgs);
const listener = new StateChangeListener(client);
// Generate two errors.
await expect(client.startRealtimeNotifications()).rejects.toThrow();
await expect(client.startRealtimeNotifications()).rejects.toThrow();
expect(listener.onChangeCalledCount).toBe(2);
const latestError = listener.state.latestErrors['ChatClient.startRealtimeNotifications'];
expect(latestError).toBeDefined();
expect(latestError).toEqual(new ChatError('ChatClient.startRealtimeNotifications', new Error('injected error #2')));
});
});