-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathchat.spec.ts
More file actions
1368 lines (1156 loc) · 44.5 KB
/
Copy pathchat.spec.ts
File metadata and controls
1368 lines (1156 loc) · 44.5 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
import { elementUpdated, expect, fixture } from '@open-wc/testing';
import { html, nothing } from 'lit';
import { spy, stub, useFakeTimers } from 'sinon';
import { configureTheme } from '../../theming/config.js';
import type IgcIconButtonComponent from '../button/icon-button.js';
import IgcChipComponent from '../chip/chip.js';
import { enterKey, tabKey } from '../common/controllers/key-bindings.js';
import { defineComponents } from '../common/definitions/defineComponents.js';
import { first, last } from '../common/util.js';
import {
isFocused,
simulateBlur,
simulateClick,
simulateFocus,
simulateInput,
simulateKeyboard,
} from '../common/utils.spec.js';
import { simulateFileUpload } from '../file-input/file-input.spec.js';
import IgcInputComponent from '../input/input.js';
import IgcListItemComponent from '../list/list-item.js';
import IgcTextareaComponent from '../textarea/textarea.js';
import IgcChatComponent from './chat.js';
import IgcChatInputComponent from './chat-input.js';
import IgcChatMessageComponent from './chat-message.js';
import IgcMessageAttachmentsComponent from './message-attachments.js';
import type {
ChatMessageRenderContext,
IgcChatMessage,
IgcChatMessageAttachment,
IgcChatOptions,
} from './types.js';
describe('Chat', () => {
before(() => {
defineComponents(IgcChatComponent, IgcInputComponent);
// Suppress ResizeObserver loop errors that can occur during tests from
// the underlying igc-textarea component. These errors do not affect the tests and are not actionable.
const errorHandler = window.onerror;
window.onerror = (message, ...args) => {
if (typeof message === 'string' && message.match(/ResizeObserver loop/)) {
return true;
}
return errorHandler ? errorHandler(message, ...args) : false;
};
});
const textInputTemplate = (text: string) => html`
<igc-input placeholder="Type text here..." .value=${text}></igc-input>
`;
const textAreaActionsTemplate = () => html`
<div class="custom-actions">
<igc-button>Upload</igc-button>
<igc-button>Send</igc-button>
</div>
`;
const textAreaAttachmentsTemplate = (
attachments: IgcChatMessageAttachment[]
) => {
return html`
<div>
${attachments.map(
(attachment) => html`
<a
href=${attachment.file
? URL.createObjectURL(attachment.file)
: (attachment.url ?? '')}
target="_blank"
>
${attachment.name}
</a>
`
)}
</div>
`;
};
const messages: IgcChatMessage[] = [
{
id: '1',
text: 'Hello! How can I help you today?',
sender: 'bot',
},
{
id: '2',
text: 'Hello!',
sender: 'user',
attachments: [
{
id: 'img1',
name: 'img1.png',
url: 'https://www.infragistics.com/angular-demos/assets/images/men/1.jpg',
type: 'image',
},
],
},
{
id: '3',
text: 'Thank you!',
sender: 'bot',
attachments: [
{
id: 'file1',
name: 'file1.other',
url: 'http://some-link-to/file1.other',
type: 'file',
},
],
},
{
id: '4',
text: 'Thank you too!',
sender: 'user',
},
];
const draftMessage = {
text: 'Draft message',
attachments: [
{
id: 'img1',
name: 'img1.png',
url: 'https://www.infragistics.com/angular-demos/assets/images/men/1.jpg',
type: 'image',
},
],
};
const files = [
new File(['test content'], 'test.txt', { type: 'text/plain' }),
new File(['image data'], 'image.png', { type: 'image/png' }),
];
let chat: IgcChatComponent;
beforeEach(async () => {
chat = await fixture<IgcChatComponent>(html`<igc-chat></igc-chat>`);
});
describe('Initialization', () => {
it('is correctly initialized with its default component state', () => {
expect(chat.messages).to.be.empty;
expect(chat.options).to.be.undefined;
expect(chat.draftMessage).to.eql({ text: '', attachments: [] });
});
it('empty chat is rendered correctly', () => {
const { emptyState, input } = getChatDOM(chat);
expect(emptyState).not.to.be.null;
expect(input.fileInput).not.to.be.null;
expect(input.textarea).not.to.be.null;
expect(input.sendButton).not.to.be.null;
});
it('should render initially set messages correctly', async () => {
chat.messages = messages;
await elementUpdated(chat);
const { messageList, messages: renderedMessages } = getChatDOM(chat);
expect(chat.messages).lengthOf(messages.length);
expect(messageList).not.to.be.null;
expect(renderedMessages).lengthOf(messages.length);
const [firstMessage, lastMessage] = [
first(renderedMessages),
last(renderedMessages),
];
// Response messages have the default reactions.
expect(getChatMessageDOM(firstMessage).defaultActionButtons).lengthOf(4);
// Current user messages does not have default reactions
expect(getChatMessageDOM(lastMessage).defaultActionButtons).to.be.empty;
});
it('should render messages from the current user correctly', async () => {
chat.messages = [
first(messages),
last(messages),
{ id: '2', text: 'Hello!', sender: 'me' },
];
chat.options = { currentUserId: 'me' };
await elementUpdated(chat);
const renderedMessages = getChatDOM(chat).messages;
const currentUserMessage = last(renderedMessages);
for (const each of renderedMessages) {
expect(
getChatMessageDOM(each).container.part.contains('sent')
).to.equal(each === currentUserMessage);
}
});
it('should render the message in `draftMessage` correctly', async () => {
chat.draftMessage = draftMessage;
await elementUpdated(chat);
const { input } = getChatDOM(chat);
expect(input.textarea.value).to.equal(draftMessage.text);
expect(input.chips).lengthOf(draftMessage.attachments.length);
});
it('should apply `headerText` correctly', async () => {
chat.options = { headerText: 'Chat' };
await elementUpdated(chat);
const { header } = getChatDOM(chat);
expect(header.innerText).to.equal(chat.options.headerText);
});
it('should apply `inputPlaceholder` correctly', async () => {
chat.options = { inputPlaceholder: 'Type message here...' };
await elementUpdated(chat);
const { input } = getChatDOM(chat);
expect(input.textarea.placeholder).to.equal(
chat.options.inputPlaceholder
);
});
it('should apply `speakPlaceholder` while recording', async () => {
chat.options = {
inputPlaceholder: 'Type message here...',
speakPlaceholder: 'Listening...',
speechToText: { enable: true, serviceProvider: 'webspeech' },
};
await elementUpdated(chat);
const { input } = getChatDOM(chat);
expect(input.textarea.placeholder).to.equal(
chat.options.inputPlaceholder
);
Reflect.set(input.self, 'isRecording', true);
input.self.requestUpdate();
await elementUpdated(input.self);
expect(input.textarea.placeholder).to.equal(
chat.options.speakPlaceholder
);
});
it('should fallback to `inputPlaceholder` while recording if `speakPlaceholder` is not set', async () => {
chat.options = {
inputPlaceholder: 'Type message here...',
speechToText: { enable: true, serviceProvider: 'webspeech' },
};
await elementUpdated(chat);
const { input } = getChatDOM(chat);
Reflect.set(input.self, 'isRecording', true);
input.self.requestUpdate();
await elementUpdated(input.self);
expect(input.textarea.placeholder).to.equal(
chat.options.inputPlaceholder
);
});
it('should render the speech-to-text button only when enabled', async () => {
chat.options = {
speechToText: { enable: true, serviceProvider: 'webspeech' },
};
await elementUpdated(chat);
let speechToTextButton = getChatDOM(
chat
).input.self.renderRoot.querySelector(
'igc-icon-button[part="speech-to-text"]'
);
expect(speechToTextButton).not.to.be.null;
chat.options = {
speechToText: { enable: false, serviceProvider: 'webspeech' },
};
await elementUpdated(chat);
speechToTextButton = getChatDOM(chat).input.self.renderRoot.querySelector(
'igc-icon-button[part="speech-to-text"]'
);
expect(speechToTextButton).to.be.null;
});
it('should pass an accessibility audit with speech-to-text enabled and disabled', async () => {
chat.options = {
inputPlaceholder: 'Type message here...',
speakPlaceholder: 'Listening...',
speechToText: { enable: true, serviceProvider: 'webspeech' },
};
await elementUpdated(chat);
await expect(chat).to.be.accessible();
await expect(chat).shadowDom.to.be.accessible();
chat.options = {
inputPlaceholder: 'Type message here...',
speechToText: { enable: false, serviceProvider: 'webspeech' },
};
await elementUpdated(chat);
await expect(chat).to.be.accessible();
await expect(chat).shadowDom.to.be.accessible();
});
it('should enable/disable the send button properly', async () => {
const { textarea, sendButton, fileInput } = getChatDOM(chat).input;
expect(sendButton.disabled).to.be.true;
// When there is a text in the text area, the send button should be enabled
let value = 'Hello!';
textarea.value = value;
textarea.emitEvent('igcInput', { detail: value });
await elementUpdated(chat);
expect(sendButton.disabled).to.be.false;
// When there is no text in the text area, the send button should be disabled
value = '';
textarea.value = value;
textarea.emitEvent('igcInput', { detail: value });
await elementUpdated(chat);
expect(sendButton.disabled).to.be.true;
// When there are attachments, the send button should be enabled regardless of the text area content
simulateFileUpload(fileInput, files);
await elementUpdated(chat);
expect(sendButton.disabled).to.be.false;
});
it('should not render attachment button if `disableInputAttachments` is true', async () => {
chat.options = { disableInputAttachments: true };
await elementUpdated(chat);
const { input } = getChatDOM(chat);
expect(input.fileInput).to.be.null;
});
it('should update the file-input accepted prop based on the `acceptedFiles`', async () => {
chat.options = { acceptedFiles: 'image/*' };
await elementUpdated(chat);
const { input } = getChatDOM(chat);
expect(input.fileInput.accept).to.equal(chat.options.acceptedFiles);
chat.options = {};
await elementUpdated(chat);
expect(input.fileInput.accept).to.be.empty;
});
it('should render attachments chips correctly', async () => {
const { input } = getChatDOM(chat);
const fileNames = new Set(files.map((file) => file.name));
simulateFileUpload(input.fileInput, files);
await elementUpdated(chat);
expect(input.chips).length(files.length);
expect(input.chips.every((chip) => fileNames.has(chip.innerText))).to.be
.true;
});
it('should not render container if suggestions are not provided', () => {
expect(getChatDOM(chat).suggestionsContainer).to.be.null;
});
it('should render suggestions if provided', async () => {
chat.options = { suggestions: ['Suggestion 1', 'Suggestion 2'] };
await elementUpdated(chat);
const { suggestionsContainer } = getChatDOM(chat);
expect(suggestionsContainer).not.to.be.null;
expect(suggestionsContainer.querySelector('igc-list')).not.to.be.null;
});
it('should render suggestions below empty state by default', async () => {
chat.options = { suggestions: ['Suggestion 1', 'Suggestion 2'] };
await elementUpdated(chat);
const { emptyState, suggestionsContainer } = getChatDOM(chat);
expect(suggestionsContainer.previousElementSibling).to.eql(emptyState);
});
it('should render suggestions below messages by default', async () => {
chat.options = { suggestions: ['Suggestion 1', 'Suggestion 2'] };
chat.messages.push({ id: '5', text: 'New message', sender: 'user' });
await elementUpdated(chat);
const { messageList, suggestionsContainer } = getChatDOM(chat);
expect(
suggestionsContainer.getBoundingClientRect().top
).to.be.greaterThanOrEqual(messageList.getBoundingClientRect().bottom);
});
it("should render suggestions below input area when position is 'below-input'", async () => {
chat.options = {
suggestions: ['Suggestion 1', 'Suggestion 2'],
suggestionsPosition: 'below-input',
};
await elementUpdated(chat);
const { input, suggestionsContainer } = getChatDOM(chat);
expect(
suggestionsContainer.getBoundingClientRect().top
).greaterThanOrEqual(input.self.getBoundingClientRect().bottom);
});
it('should render typing indicator if `isTyping` is true', async () => {
chat.options = { isTyping: true };
await elementUpdated(chat);
expect(getChatDOM(chat).typingIndicator).not.to.be.null;
chat.options = { isTyping: false };
await elementUpdated(chat);
expect(getChatDOM(chat).typingIndicator).to.be.null;
});
});
describe('Slots', () => {
const getSlottedElements = (slotName: string) => {
const prefixSlot = chat.shadowRoot?.querySelector(
`slot[name="${slotName}"`
) as HTMLSlotElement;
return prefixSlot?.assignedElements();
};
const suggestions = ['Login screen', 'Registration Form'];
beforeEach(async () => {
chat = await fixture<IgcChatComponent>(html`
<igc-chat>
<div slot="prefix">
<igc-button variant="flat">⋯</igc-button>
</div>
<h4 slot="title">Title</h4>
<div slot="actions">
<igc-button variant="flat">?</igc-button>
</div>
<span slot="empty-state">What do you want to build?</span>
<h3 slot="suggestions-header">Get inspired</h3>
<div slot="suggestions">
${suggestions.map((suggestion, index) => {
return html`
<div slot="suggestion">
<span>${index}. ${suggestion}</span>
<igc-icon name="good-response"></igc-icon>
</div>
`;
})}
</div>
<h3 slot="suggestions-actions">Add more ...</h3>
</igc-chat>
`);
chat.options = { ...chat.options, suggestions };
await elementUpdated(chat);
});
it('should slot header prefix', () => {
const slottedElements = getSlottedElements('prefix');
expect(slottedElements.length).to.equal(1);
expect(slottedElements[0]).dom.to.equal(
`<div slot="prefix">
<igc-button type="button" variant="flat">⋯</igc-button>
</div>`
);
});
it('should slot header title', () => {
const slottedElements = getSlottedElements('title');
expect(slottedElements.length).to.equal(1);
expect(slottedElements[0]).dom.to.equal(`<h4 slot="title">Title</h4>`);
});
it('should slot header action buttons area', () => {
const slottedElements = getSlottedElements('actions');
expect(slottedElements.length).to.equal(1);
expect(slottedElements[0]).dom.to.equal(
`<div slot="actions">
<igc-button type="button" variant="flat">?</igc-button>
</div>`
);
});
it('should slot message list area when there are no messages', () => {
const slottedElements = getSlottedElements('empty-state');
expect(slottedElements.length).to.equal(1);
expect(slottedElements[0]).dom.to.equal(
`<span slot="empty-state">What do you want to build?</span>`
);
});
it('should slot suggestions header', async () => {
const slottedElements = getSlottedElements('suggestions-header');
expect(slottedElements?.length).to.equal(1);
expect(slottedElements[0]).dom.to.equal(
`<h3 slot="suggestions-header">Get inspired</h3>`
);
});
it('should slot suggestions area', async () => {
const slottedElements = getSlottedElements('suggestions');
expect(slottedElements?.length).to.equal(1);
expect(slottedElements[0]).dom.to.equal(`<div slot="suggestions">
<div slot="suggestion">
<span>
0. Login screen
</span>
<igc-icon
name="good-response"
>
</igc-icon>
</div>
<div slot="suggestion">
<span>
1. Registration Form
</span>
<igc-icon
name="good-response"
>
</igc-icon>
</div>
</div>`);
});
it('should slot suggestions actions area', async () => {
const slottedElements = getSlottedElements('suggestions-actions');
expect(slottedElements?.length).to.equal(1);
expect(slottedElements[0]).dom.to.equal(
`<h3 slot="suggestions-actions">Add more ...</h3>`
);
});
});
describe('Templates', () => {
beforeEach(async () => {
chat.messages = [messages[1], messages[2]];
});
it('should render attachment template', async () => {
chat.options = {
renderers: {
attachment: ({ attachment }) => html`
<igc-chip class="custom-attachment">
<span>${attachment.name}</span>
</igc-chip>
`,
},
};
await elementUpdated(chat);
const { messages } = getChatDOM(chat);
const attachments = messages.flatMap(
(message) => getChatMessageDOM(message).attachments
);
for (const attachment of attachments) {
expect(
getChatAttachmentDOM(attachment).container.querySelector(
'igc-chip.custom-attachment'
)
).not.to.be.null;
}
});
it('should render attachmentHeader template, attachmentContent template', async () => {
chat.options = {
renderers: {
attachmentHeader: ({ attachment }) =>
html`<h5>Custom ${attachment.name}</h5>`,
attachmentContent: ({ attachment }) => html`
<p>This is a template rendered as content of ${attachment.name}</p>
`,
},
};
await elementUpdated(chat);
const { messages } = getChatDOM(chat);
const attachments = messages.flatMap(
(message) => getChatMessageDOM(message).attachments
);
for (const attachment of attachments) {
const { header, content } = getChatAttachmentDOM(attachment);
expect(header.querySelector('h5')?.innerText).matches(/^Custom/);
expect(content.querySelector('p')?.innerText).matches(
/^This is a template/
);
}
});
it('should render message template', async () => {
chat.options = {
renderers: {
message: ({ message }) => html`
<div>
<h5>${message.sender === 'user' ? 'You' : 'Bot'}</h5>
<p>${message.text}</p>
</div>
`,
},
};
await elementUpdated(chat);
for (const message of getChatDOM(chat).messages) {
expect(
getChatMessageDOM(message).container.querySelector('h5')?.innerText
).to.equal(message.message.sender === 'user' ? 'You' : 'Bot');
}
});
it('should render messageContent template', async () => {
chat.options = {
renderers: {
messageContent: ({ message }) => html`${message.text.toUpperCase()}`,
},
};
await elementUpdated(chat);
for (const [index, message] of getChatDOM(chat).messages.entries()) {
expect(getChatMessageDOM(message).content.innerText).to.equal(
chat.messages[index].text.toUpperCase()
);
}
});
it('should render messageActionsTemplate', async () => {
chat.options = {
renderers: {
messageActions: ({ message }) =>
message.sender !== 'user'
? html`<button>Custom action</button>`
: nothing,
},
};
await elementUpdated(chat);
for (const message of getChatDOM(chat).messages) {
expect(getChatMessageDOM(message).actions.innerText).to.equal(
message.message.sender === 'user' ? '' : 'Custom action'
);
}
});
it('should render custom typingIndicator', async () => {
const indicator = document.createElement('span');
indicator.slot = 'typing-indicator';
indicator.innerText = 'loading...';
chat.appendChild(indicator);
chat.messages = [messages[0]];
chat.options = { isTyping: true };
await elementUpdated(chat);
const typingIndicator = getChatDOM(chat).typingIndicator;
const assignedElements = typingIndicator
?.querySelector('slot')
?.assignedElements();
expect(first(assignedElements!).textContent).to.equal('loading...');
});
it('should render text area templates', async () => {
chat.draftMessage = draftMessage;
chat.options = {
renderers: {
input: (ctx) => textInputTemplate(ctx.value),
inputActions: () => textAreaActionsTemplate(),
inputAttachments: (ctx) =>
textAreaAttachmentsTemplate(ctx.attachments),
},
};
await elementUpdated(chat);
const { self: inputArea, sendButton, fileInput } = getChatDOM(chat).input;
expect(inputArea.renderRoot.querySelector('igc-input')?.value).to.equal(
draftMessage.text
);
expect(inputArea.renderRoot.querySelector('a')?.href).to.equal(
draftMessage.attachments[0].url
);
expect(sendButton).to.be.null;
expect(fileInput).to.be.null;
var customActions =
inputArea.renderRoot.querySelector('div.custom-actions');
expect(customActions).not.to.be.null;
});
it('should render messageHeader template', async () => {
chat.options = {
renderers: {
messageHeader: ({ message }) =>
html`${message.sender !== 'user' ? 'AI Assistant' : ''}`,
},
};
await elementUpdated(chat);
for (const message of getChatDOM(chat).messages) {
expect(getChatMessageDOM(message).header.innerText).to.equal(
message.message.sender === 'user' ? '' : 'AI Assistant'
);
}
});
});
describe('Interactions', () => {
describe('Click', () => {
it('should update messages properly on send button click', async () => {
const eventSpy = spy(chat, 'emitEvent');
const { textarea, sendButton } = getChatDOM(chat).input!;
textarea.setAttribute('value', 'Hello!');
textarea.dispatchEvent(
new CustomEvent('igcInput', { detail: 'Hello!' })
);
await elementUpdated(chat);
simulateClick(sendButton);
await elementUpdated(chat);
expect(eventSpy).calledWith('igcMessageCreated');
const eventArgs = eventSpy.getCall(1).args[1]?.detail as IgcChatMessage;
const args = { ...eventArgs, text: 'Hello!', sender: 'user' };
expect(eventArgs).to.deep.equal(args);
expect(chat.messages.length).to.equal(1);
expect(chat.messages[0].text).to.equal('Hello!');
expect(chat.messages[0].sender).to.equal('user');
// The focus should be on the input area after send button is clicked
expect(isFocused(textarea)).to.be.true;
});
it('should update messages properly on suggestion chip click', async () => {
const eventSpy = spy(chat, 'emitEvent');
chat.options = {
suggestions: ['Suggestion 1', 'Suggestion 2'],
};
await elementUpdated(chat);
const suggestionItems = getChatDOM(
chat
).suggestionsContainer.querySelectorAll(IgcListItemComponent.tagName);
expect(suggestionItems.length).to.equal(2);
simulateClick(suggestionItems[0]);
await elementUpdated(chat);
expect(eventSpy).calledWith('igcMessageCreated');
const eventArgs = eventSpy.getCall(0).args[1]?.detail;
const args =
eventArgs && typeof eventArgs === 'object'
? { ...eventArgs, text: 'Suggestion 1', sender: 'user' }
: { text: 'Suggestion 1', sender: 'user' };
expect(eventArgs).to.deep.equal(args);
expect(chat.messages.length).to.equal(1);
expect(chat.messages[0].text).to.equal('Suggestion 1');
expect(chat.messages[0].sender).to.equal('user');
// The focus should be on the input area after suggestion click
expect(isFocused(getChatDOM(chat).input.textarea)).to.be.true;
});
it('should remove attachment on chip remove button click', async () => {
const eventSpy = spy(chat, 'emitEvent');
const fileInput = getChatDOM(chat).input.fileInput;
simulateFileUpload(fileInput, files);
await elementUpdated(chat);
expect(eventSpy).calledOnce;
expect(eventSpy.calledWith('igcAttachmentAdded')).to.be.true;
const attachments = getChatDOM(chat).input.chips;
expect(attachments.length).to.equal(2);
const removeFileButton = attachments[1]?.renderRoot.querySelector(
'igc-icon'
) as HTMLElement;
simulateClick(removeFileButton);
await elementUpdated(chat);
expect(eventSpy).calledTwice;
expect(eventSpy.calledWith('igcAttachmentRemoved')).to.be.true;
const detail = eventSpy.getCall(1).args[1]?.detail;
expect((detail as IgcChatMessageAttachment).name).to.equal(
files[1].name
);
});
it('should disable send button on removing all attachments', async () => {
const inputArea = getChatDOM(chat).input!;
const { fileInput, sendButton } = inputArea;
simulateFileUpload(fileInput, files);
await elementUpdated(chat);
const attachments = inputArea.chips;
simulateClick(attachments[1].renderRoot.querySelector('igc-icon')!);
simulateClick(attachments[0].renderRoot.querySelector('igc-icon')!);
await elementUpdated(inputArea.self);
expect(sendButton.disabled).to.be.true;
});
it('should update like button state on click', async () => {
chat.messages = [messages[0]];
await elementUpdated(chat);
const firstMessage = getChatDOM(chat).messages[0];
// click on like (inactive) icon
const likeIcon =
getChatMessageDOM(firstMessage).defaultActionButtons[1];
simulateClick(likeIcon);
await elementUpdated(chat);
expect(likeIcon.name).to.equal('thumb_up_active');
// click on like (active) icon
simulateClick(likeIcon);
await elementUpdated(chat);
expect(likeIcon.name).to.equal('thumb_up_inactive');
// click on like (inactive) icon
simulateClick(likeIcon);
await elementUpdated(chat);
expect(likeIcon.name).to.equal('thumb_up_active');
});
it('should toggle like/dislike state on click', async () => {
chat.messages = [messages[0]];
await elementUpdated(chat);
const firstMessage = getChatDOM(chat).messages[0];
// click on like (inactive) icon
const likeIcon =
getChatMessageDOM(firstMessage).defaultActionButtons[1];
simulateClick(likeIcon);
await elementUpdated(chat);
const dislikeIcon =
getChatMessageDOM(firstMessage).defaultActionButtons[2];
expect(dislikeIcon.name).to.equal('thumb_down_inactive');
// click on dislike (active) icon
simulateClick(dislikeIcon);
await elementUpdated(chat);
expect(likeIcon.name).to.equal('thumb_up_inactive');
expect(dislikeIcon.name).to.equal('thumb_down_active');
// click on like (inactive) icon
simulateClick(likeIcon);
await elementUpdated(chat);
expect(likeIcon.name).to.equal('thumb_up_active');
});
it('should handle the copy action properly', async () => {
const clipboardWriteText = stub(
navigator.clipboard,
'writeText'
).resolves();
chat.messages = [messages[0]];
await elementUpdated(chat);
expect(clipboardWriteText.called).to.be.false;
const firstMessage =
chat.shadowRoot?.querySelectorAll('igc-chat-message')[0];
// click on copy icon
const copyIcon = firstMessage?.shadowRoot?.querySelector(
'igc-icon-button[name="copy_content"]'
) as HTMLElement;
simulateClick(copyIcon);
await elementUpdated(chat);
expect(clipboardWriteText.called).to.be.true;
});
});
describe('Drag & Drop', () => {
beforeEach(async () => {
const options = {
acceptedFiles: '.txt',
};
chat = await fixture<IgcChatComponent>(
html`<igc-chat .options=${options}> </igc-chat>`
);
});
it('should be able to drag & drop files based on the types listed in `acceptedFiles`', async () => {
const eventSpy = spy(chat, 'emitEvent');
const inputArea = getChatDOM(chat).input.self!;
const dropZone = inputArea?.renderRoot.querySelector(
`div[part='input-container']`
);
expect(dropZone).not.to.be.null;
if (dropZone) {
const mockDataTransfer = new DataTransfer();
files.forEach((file) => {
mockDataTransfer.items.add(file);
});
const dragEnterEvent = new DragEvent('dragenter', {
bubbles: true,
cancelable: true,
});
Object.defineProperty(dragEnterEvent, 'dataTransfer', {
value: mockDataTransfer,
});
dropZone?.dispatchEvent(dragEnterEvent);
await elementUpdated(chat);
expect(eventSpy).calledOnce;
expect(eventSpy).calledWith('igcAttachmentDrag');
const dropEvent = new DragEvent('drop', {
bubbles: true,
cancelable: true,
});
Object.defineProperty(dropEvent, 'dataTransfer', {
value: mockDataTransfer,
});
dropZone.dispatchEvent(dropEvent);
await elementUpdated(chat);
expect(eventSpy).calledWith('igcAttachmentDrop');
const attachments = getChatDOM(chat).input.chips;
expect(attachments?.length).to.equal(1);
expect(attachments?.[0]?.textContent?.trim()).to.equal('test.txt');
expect(eventSpy).calledWith('igcAttachmentDrop');
expect(eventSpy).calledWith('igcAttachmentAdded');
}
});
});
describe('Keyboard', () => {
it('should update messages properly on `Enter` keypress when the textarea is focused', async () => {
const eventSpy = spy(chat, 'emitEvent');
const textArea = getChatDOM(chat).input.textarea;
textArea.setAttribute('value', 'Hello!');
textArea.dispatchEvent(
new CustomEvent('igcInput', { detail: 'Hello!' })
);
await elementUpdated(chat);
simulateFocus(textArea);
simulateKeyboard(textArea, enterKey);
await elementUpdated(chat);
expect(eventSpy).calledWith('igcMessageCreated');
const eventArgs = eventSpy.getCall(2).args[1]?.detail;
const args =
eventArgs && typeof eventArgs === 'object'
? { ...eventArgs, text: 'Hello!', sender: 'user' }
: { text: 'Hello!', sender: 'user' };
expect(eventArgs).to.deep.equal(args);
expect(chat.messages.length).to.equal(1);
expect(chat.messages[0].text).to.equal('Hello!');
expect(chat.messages[0].sender).to.equal('user');
// The focus should be on the input area after message is sent
expect(isFocused(textArea)).to.be.true;
});
});
});
describe('Events', () => {
it('emits igcAttachmentClick', async () => {
const eventSpy = spy(chat, 'emitEvent');
chat.messages = [messages[1]];
await elementUpdated(chat);
const messageElement = getChatDOM(chat).messages[0];
const attachment = getChatMessageDOM(messageElement).attachments[0];
const attachmentHeader = getChatAttachmentDOM(attachment).header;
simulateClick(attachmentHeader);
expect(eventSpy).calledWith('igcAttachmentClick', {
detail: { ...messages[1].attachments?.at(0) },
});
});
it('emits igcTypingChange', async () => {
const clock = useFakeTimers({ now: 0, toFake: ['Date', 'setTimeout'] });
const eventSpy = spy(chat, 'emitEvent');
const textArea = getChatDOM(chat).input.textarea;
chat.options = { stopTypingDelay: 2500 };
simulateKeyboard(textArea, 'a', 15);
await elementUpdated(chat);
expect(eventSpy).calledWith('igcTypingChange');
expect(eventSpy.firstCall.args[1]?.detail).to.be.true;