-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathautocomplete.test.js
More file actions
972 lines (801 loc) · 30.1 KB
/
Copy pathautocomplete.test.js
File metadata and controls
972 lines (801 loc) · 30.1 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
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { formatGroup, formatResult } from "../src/format.ts";
const $ = globalThis.jQuery;
// Clear mockjax handlers and any leftover suggestion containers between tests
// so describe blocks don't leak state into each other.
afterEach(() => {
$.mockjax.clear();
$(".autocomplete-suggestions").remove();
});
describe("Autocomplete Async — onSearchStart", () => {
const input = document.createElement("input");
let startQuery;
let ajaxExecuted = false;
const autocomplete = new $.Autocomplete(input, {
serviceUrl: "/test",
onSearchStart: function (params) {
startQuery = params.query;
},
});
beforeEach(async () => {
await new Promise((resolve) => {
$.mockjax({
url: "/test",
responseTime: 50,
response: function (settings) {
ajaxExecuted = true;
const query = settings.data.query;
this.responseText = JSON.stringify({ query, suggestions: [] });
resolve();
},
});
input.value = "A";
autocomplete.onValueChange();
});
});
it("Should execute onSearchStart", () => {
expect(ajaxExecuted).toBe(true);
expect(startQuery).toBe("A");
});
});
describe("Autocomplete Async — onSearchComplete", () => {
const input = document.createElement("input");
const mockupSuggestion = { value: "A", data: "A" };
let completeQuery;
let resultSuggestions;
let ajaxExecuted = false;
const url = "/test-completed";
beforeEach(async () => {
await new Promise((resolve) => {
const autocomplete = new $.Autocomplete(input, {
serviceUrl: url,
onSearchComplete: function (query, suggestions) {
completeQuery = query;
resultSuggestions = suggestions;
resolve();
},
});
$.mockjax({
url,
responseTime: 50,
response: function (settings) {
ajaxExecuted = true;
const query = settings.data.query;
this.responseText = JSON.stringify({
query,
suggestions: [mockupSuggestion],
});
},
});
input.value = "A";
autocomplete.onValueChange();
});
});
it("Should execute onSearchComplete", () => {
expect(ajaxExecuted).toBe(true);
expect(completeQuery).toBe("A");
expect(resultSuggestions[0].value).toBe("A");
expect(resultSuggestions[0].data).toBe("A");
});
});
describe("Autocomplete Async — onSearchError", () => {
let errorMessage = false;
beforeEach(async () => {
await new Promise((resolve) => {
const input = document.createElement("input");
const url = "/test-error";
const autocomplete = new $.Autocomplete(input, {
serviceUrl: url,
onSearchError: function (q, jqXHR /*, textStatus, errorThrown */) {
errorMessage = jqXHR.responseText;
resolve();
},
});
$.mockjax({
url,
responseTime: 50,
status: 500,
response: function () {
this.responseText = "An error occurred";
},
});
input.value = "A";
autocomplete.onValueChange();
});
});
it("Should execute onSearchError", () => {
expect(errorMessage).toBe("An error occurred");
});
});
describe("Autocomplete Async — transformResult", () => {
let instance;
beforeEach(async () => {
await new Promise((resolve) => {
const input = document.createElement("input");
const url = "/test-transform";
const autocomplete = new $.Autocomplete(input, {
serviceUrl: url,
transformResult: function (result, query) {
// call resolve after we return;
setTimeout(resolve, 0);
return {
query,
suggestions: $.map(result.split(","), function (item) {
return { value: item, data: null };
}),
};
},
});
$.mockjax({
url,
responseTime: 50,
response: function () {
this.responseText = "Andora,Angola,Argentina";
},
});
instance = autocomplete;
input.value = "A";
autocomplete.onValueChange();
});
});
it("Should transform results", () => {
expect(instance.suggestions.length).toBe(3);
expect(instance.suggestions[0].value).toBe("Andora");
});
});
describe("Autocomplete Async — optional server query field", () => {
let instance;
beforeEach(async () => {
await new Promise((resolve) => {
const input = document.createElement("input");
const url = "/test-original-query";
const autocomplete = new $.Autocomplete(input, { serviceUrl: url });
$.mockjax({
url,
responseTime: 50,
response: function () {
const response = {
query: null,
suggestions: ["Aa", "Bb", "Cc"],
};
this.responseText = JSON.stringify(response);
setTimeout(resolve, 0);
},
});
input.value = "A";
instance = autocomplete;
autocomplete.onValueChange();
});
});
it("Should not require original query value from the server", () => {
expect(instance.suggestions.length).toBe(3);
expect(instance.suggestions[0].value).toBe("Aa");
});
});
describe("Autocomplete Async — custom paramName", () => {
let paramValue;
beforeEach(async () => {
await new Promise((resolve) => {
const input = document.createElement("input");
const paramName = "custom";
const autocomplete = new $.Autocomplete(input, {
serviceUrl: "/test-query",
paramName,
});
$.mockjax({
url: "/test-query",
responseTime: 5,
response: function (settings) {
paramValue = settings.data[paramName];
this.responseText = JSON.stringify({
query: paramValue,
suggestions: [],
});
resolve();
},
});
input.value = "Jam";
autocomplete.onValueChange();
});
});
it("Should use custom query parameter name", () => {
expect(paramValue).toBe("Jam");
});
});
describe("Autocomplete Async — serviceUrl as callback", () => {
let dynamicUrl;
let data;
beforeEach(async () => {
await new Promise((resolve) => {
const input = $(document.createElement("input"));
input.autocomplete({
ignoreParams: true,
serviceUrl: function (query) {
return "/dynamic-url/" + encodeURIComponent(query).replace(/%20/g, "+");
},
});
$.mockjax({
url: "/dynamic-url/*",
responseTime: 5,
response: function (settings) {
dynamicUrl = settings.url;
data = settings.data;
this.responseText = JSON.stringify({ suggestions: [] });
resolve();
},
});
input.val("Hello World");
input.autocomplete().onValueChange();
});
});
it("Should construct serviceUrl via callback function.", () => {
expect(dynamicUrl).toBe("/dynamic-url/Hello+World");
expect(data).toBeFalsy();
});
});
describe("Autocomplete Async — cache key", () => {
let instance;
let cacheKey;
beforeEach(async () => {
await new Promise((resolve) => {
const input = $("<input />");
const data = { a: 1, query: "Jam" };
const serviceUrl = "/autocomplete/cached/url";
cacheKey = serviceUrl + "?" + $.param(data);
input.autocomplete({
serviceUrl,
params: data,
});
$.mockjax({
url: serviceUrl,
responseTime: 5,
response: function () {
this.responseText = JSON.stringify({
suggestions: [{ value: "Jamaica" }, { value: "Jamaica" }],
});
setTimeout(resolve, 10);
},
});
input.val("Jam");
instance = input.autocomplete();
instance.onValueChange();
});
});
it("Should use serviceUrl and params as cacheKey", () => {
expect(instance.cachedResponse[cacheKey]).toBeTruthy();
});
});
describe("Autocomplete Async — preventBadQueries", () => {
let ajaxCount = 0;
beforeEach(async () => {
await new Promise((resolve) => {
const input = $("<input />");
let instance;
const serviceUrl = "/autocomplete/prevent/ajax";
input.autocomplete({ serviceUrl });
$.mockjax({
url: serviceUrl,
responseTime: 1,
response: function () {
ajaxCount += 1;
this.responseText = JSON.stringify({ suggestions: [] });
if (ajaxCount === 2) {
resolve();
}
},
});
setTimeout(() => {
input.val("Jam");
instance = input.autocomplete();
instance.onValueChange();
}, 10);
setTimeout(() => {
input.val("Jama");
instance.onValueChange();
}, 20);
setTimeout(() => {
instance.setOptions({ preventBadQueries: false });
input.val("Jamai");
instance.onValueChange();
}, 30);
});
});
it("Should prevent Ajax requests if previous query with matching root failed.", () => {
// Ajax call should have been made twice (then short-circuited by the
// bad-query guard until preventBadQueries was disabled).
expect(ajaxCount).toBe(2);
});
});
describe("Autocomplete Async — empty originalQuery", () => {
it("does not push an empty originalQuery onto badQueries", async () => {
const input = $("<input />");
const serviceUrl = "/autocomplete/empty-bad-query";
let ajaxCount = 0;
input.autocomplete({
serviceUrl,
minChars: 0,
preventBadQueries: true,
});
const instance = input.autocomplete();
$.mockjax({
url: serviceUrl,
responseTime: 1,
response: function () {
ajaxCount += 1;
this.responseText = JSON.stringify({ suggestions: [] });
},
});
// First lookup: empty query with no results.
input.val("");
instance.onValueChange();
await new Promise((r) => setTimeout(r, 30));
// Second lookup: real query — must not be short-circuited by an empty
// prefix sitting in badQueries.
input.val("Jam");
instance.onValueChange();
await new Promise((r) => setTimeout(r, 30));
expect(instance.badQueries).not.toContain("");
expect(ajaxCount).toBe(2);
});
});
describe("Autocomplete", () => {
afterEach(() => {
$(".autocomplete-suggestions").hide();
});
it("Should initialize autocomplete options", () => {
const input = document.createElement("input");
const options = { serviceUrl: "/autocomplete/service/url" };
const autocomplete = new $.Autocomplete(input, options);
expect(autocomplete.options.serviceUrl).toEqual(options.serviceUrl);
expect(autocomplete.suggestionsContainer).not.toBeNull();
});
it('Should set autocomplete attribute to "off"', () => {
const input = document.createElement("input");
const autocomplete = new $.Autocomplete(input, {});
expect(autocomplete).not.toBeNull();
expect(input.getAttribute("autocomplete")).toEqual("off");
});
it("Should get current value", () => {
const input = document.createElement("input");
const autocomplete = new $.Autocomplete(input, {
lookup: [{ value: "Jamaica", data: "B" }],
});
input.value = "Jam";
autocomplete.onValueChange();
expect(autocomplete.visible).toBe(true);
expect(autocomplete.currentValue).toEqual("Jam");
});
it("Should call formatResult three times", () => {
const input = document.createElement("input");
let counter = 0;
let suggestion;
let currentValue;
const autocomplete = new $.Autocomplete(input, {
lookup: ["Jamaica", "Jamaica", "Jamaica"],
formatResult: function (s, v) {
suggestion = s;
currentValue = v;
counter += 1;
},
});
input.value = "Jam";
autocomplete.onValueChange();
expect(suggestion.value).toBe("Jamaica");
expect(suggestion.data).toBe(null);
expect(currentValue).toEqual("Jam");
expect(counter).toEqual(3);
});
it("Verify onSelect callback", () => {
const input = document.createElement("input");
let context;
let value;
let data;
const autocomplete = $(input)
.autocomplete({
lookup: [{ value: "A", data: "B" }],
triggerSelectOnValidInput: false,
onSelect: function (suggestion) {
context = this;
value = suggestion.value;
data = suggestion.data;
},
})
.autocomplete();
input.value = "A";
autocomplete.onValueChange();
autocomplete.select(0);
expect(context).toEqual(input);
expect(value).toEqual("A");
expect(data).toEqual("B");
});
it("Should convert suggestions format", () => {
const input = document.createElement("input");
const autocomplete = new $.Autocomplete(input, {
lookup: ["A", "B"],
});
expect(autocomplete.options.lookup[0].value).toBe("A");
expect(autocomplete.options.lookup[1].value).toBe("B");
});
it("Should not preventDefault when tabDisabled is set to false", () => {
const input = document.createElement("input");
const autocomplete = new $.Autocomplete(input, {
lookup: [{ value: "Jamaica", data: "B" }],
tabDisabled: false,
autoSelectFirst: true,
});
input.value = "Jam";
autocomplete.onValueChange();
const event = $.Event("keydown");
event.which = 9; // the tab keycode
vi.spyOn(event, "stopImmediatePropagation");
vi.spyOn(event, "preventDefault");
vi.spyOn(autocomplete, "suggest");
expect(autocomplete.visible).toBe(true);
expect(autocomplete.disabled).toBe(undefined);
expect(autocomplete.selectedIndex).not.toBe(-1);
$(input).trigger(event);
expect(event.stopImmediatePropagation).not.toHaveBeenCalled();
expect(event.preventDefault).not.toHaveBeenCalled();
expect(autocomplete.suggest).not.toHaveBeenCalled();
});
it("Should preventDefault when tabDisabled is set to true", () => {
const input = document.createElement("input");
const autocomplete = new $.Autocomplete(input, {
lookup: [{ value: "Jamaica", data: "B" }],
tabDisabled: true,
autoSelectFirst: true,
});
input.value = "Jam";
autocomplete.onValueChange();
const event = $.Event("keydown");
event.which = 9; // the tab keycode
vi.spyOn(autocomplete, "suggest");
expect(autocomplete.visible).toBe(true);
expect(autocomplete.disabled).toBe(undefined);
expect(autocomplete.selectedIndex).not.toBe(-1);
$(input).trigger(event);
expect(autocomplete.suggest).not.toHaveBeenCalled();
});
it("Should not autoselect first item by default", () => {
const input = document.createElement("input");
const autocomplete = new $.Autocomplete(input, {
lookup: ["Jamaica", "Jamaica", "Jamaica"],
});
input.value = "Jam";
autocomplete.onValueChange();
expect(autocomplete.selectedIndex).toBe(-1);
});
it("Should autoselect first item when autoSelectFirst is true", () => {
const input = document.createElement("input");
const autocomplete = new $.Autocomplete(input, {
lookup: ["Jamaica", "Jamaica", "Jamaica"],
autoSelectFirst: true,
});
input.value = "Jam";
autocomplete.onValueChange();
expect(autocomplete.selectedIndex).toBe(0);
});
it("Should destroy autocomplete instance", () => {
const input = $(document.createElement("input"));
const div = $(document.createElement("div"));
input.autocomplete({
serviceUrl: "/test-dispose",
appendTo: div,
});
expect(input.data("autocomplete")).toBeDefined();
expect(div.children().length).toBeGreaterThan(0);
input.autocomplete("dispose");
expect(input.data("autocomplete")).toBeUndefined();
expect(div.children().length).toBe(0);
});
it("Should return Autocomplete instance if called without arguments", () => {
const input = $(document.createElement("input"));
input.autocomplete({ serviceUrl: "/test-dispose" });
const instance = input.autocomplete();
expect(instance instanceof $.Autocomplete).toBe(true);
});
it("Should set width to be greater than zero", () => {
const input = $(document.createElement("input"));
input.autocomplete({
lookup: [{ value: "Jamaica", data: "B" }],
});
input.val("Jam");
input.width(100);
const instance = input.autocomplete();
instance.onValueChange();
const width = $(instance.suggestionsContainer).width();
expect(width).toBeGreaterThan(0);
});
it("Should call beforeRender and pass container jQuery object", () => {
const element = document.createElement("input");
const input = $(element);
let elementCount;
let context;
input.autocomplete({
lookup: [{ value: "Jamaica", data: "B" }],
beforeRender: function (container) {
context = this;
elementCount = container.length;
},
});
input.val("Jam");
const instance = input.autocomplete();
instance.onValueChange();
expect(context).toBe(element);
expect(elementCount).toBe(1);
});
it("Should trigger select when input value matches suggestion", () => {
const input = $("<input />");
let suggestionData = false;
input.autocomplete({
lookup: [{ value: "Jamaica", data: "J" }],
triggerSelectOnValidInput: true,
onSelect: function (suggestion) {
suggestionData = suggestion.data;
},
});
input.val("Jamaica");
const instance = input.autocomplete();
instance.onValueChange();
expect(suggestionData).toBe("J");
});
it("Should NOT trigger select when input value matches suggestion", () => {
const input = $("<input />");
let suggestionData = null;
input.autocomplete({
lookup: [{ value: "Jamaica", data: "J" }],
triggerSelectOnValidInput: false,
onSelect: function (suggestion) {
suggestionData = suggestion.data;
},
});
input.val("Jamaica");
const instance = input.autocomplete();
instance.onValueChange();
expect(suggestionData).toBeNull();
});
it("Should limit results for local request", () => {
const input = $("<input />");
const limit = 3;
input.autocomplete({
lookup: [
{ value: "Jamaica" },
{ value: "Jamaica" },
{ value: "Jamaica" },
{ value: "Jamaica" },
{ value: "Jamaica" },
],
});
input.val("Jam");
const instance = input.autocomplete();
instance.onValueChange();
expect(instance.suggestions.length).toBe(5);
instance.setOptions({ lookupLimit: limit });
instance.onValueChange();
expect(instance.suggestions.length).toBe(limit);
});
it("Should display no suggestion notice when no matching results", () => {
const input = document.createElement("input");
const options = {
lookup: [{ value: "Colombia", data: "Spain" }],
showNoSuggestionNotice: true,
noSuggestionNotice: "Sorry, no matching results",
};
const autocomplete = new $.Autocomplete(input, options);
const suggestionsContainer = $(autocomplete.suggestionsContainer);
input.value = "Jamaica";
autocomplete.onValueChange();
expect(autocomplete.visible).toBe(true);
expect(autocomplete.selectedIndex).toBe(-1);
expect(suggestionsContainer.find(".autocomplete-no-suggestion").length).toBe(1);
expect(suggestionsContainer.find(".autocomplete-no-suggestion").text()).toBe(
"Sorry, no matching results"
);
});
it("Should call onHide and pass container jQuery object", () => {
const element = document.createElement("input");
const input = $(element);
let elementCount;
let context;
input.autocomplete({
lookup: [{ value: "Jamaica", data: "B" }],
onHide: function (container) {
context = this;
elementCount = container.length;
},
});
input.val("Jam");
const instance = input.autocomplete();
instance.onValueChange();
input.val("Colombia");
instance.onValueChange();
expect(context).toBe(element);
expect(elementCount).toBe(1);
});
});
describe("Autocomplete non-string suggestion values", () => {
afterEach(() => {
$(".autocomplete-suggestions").remove();
});
it("coerces numeric value from a local lookup so render does not throw", () => {
const input = document.createElement("input");
const autocomplete = new $.Autocomplete(input, {
lookup: [{ value: 12345, data: "n" }],
triggerSelectOnValidInput: false,
});
input.value = "1";
expect(() => autocomplete.onValueChange()).not.toThrow();
expect(typeof autocomplete.suggestions[0].value).toBe("string");
expect(autocomplete.suggestions[0].value).toBe("12345");
});
it("coerces numeric value from a function lookup callback", () => {
const input = document.createElement("input");
let completedValueType;
let selectedValueType;
const autocomplete = new $.Autocomplete(input, {
lookup: (_q, done) => done({ suggestions: [{ value: 42, data: "n" }] }),
onSearchComplete: (_q, suggestions) => {
completedValueType = typeof suggestions[0].value;
},
onSelect: (suggestion) => {
selectedValueType = typeof suggestion.value;
},
});
input.value = "42";
autocomplete.onValueChange();
expect(completedValueType).toBe("string");
expect(selectedValueType).toBe("string");
});
});
describe("Autocomplete event ordering", () => {
afterEach(() => {
$(".autocomplete-suggestions").remove();
});
it("fires onSearchComplete before onSelect when a single match auto-selects", () => {
const input = document.createElement("input");
const calls = [];
const autocomplete = new $.Autocomplete(input, {
lookup: [{ value: "Apple", data: 1 }],
onSearchComplete: () => calls.push("searchComplete"),
onSelect: () => calls.push("select"),
});
input.value = "Apple";
autocomplete.onValueChange();
expect(calls).toEqual(["searchComplete", "select"]);
});
});
describe("Autocomplete groupBy", () => {
afterEach(() => {
$(".autocomplete-suggestions").remove();
});
it("regroups interleaved categories under a single header each", () => {
const input = document.createElement("input");
const lookup = [
{ value: "Anaheim Ducks", data: { category: "NHL" } },
{ value: "Portland Trail Blazers", data: { category: "NBA" } },
{ value: "Chicago Blackhawks", data: { category: "NHL" } },
{ value: "Boston BlCeltics", data: { category: "NBA" } },
{ value: "Columbus Blue Jackets", data: { category: "NHL" } },
];
const autocomplete = new $.Autocomplete(input, {
lookup,
groupBy: "category",
triggerSelectOnValidInput: false,
});
input.value = "bl";
autocomplete.onValueChange();
// 4 of 5 entries match "bl"; reordered so NBA (first-seen group with
// a match) renders first, then NHL.
expect(autocomplete.suggestions.map((s) => s.data.category)).toEqual([
"NBA",
"NBA",
"NHL",
"NHL",
]);
// One group header per distinct category, not per category boundary.
const headers = $(".autocomplete-group");
expect(headers.length).toBe(2);
expect(headers.eq(0).text()).toBe("NBA");
expect(headers.eq(1).text()).toBe("NHL");
});
it("preserves relative order within each category", () => {
const input = document.createElement("input");
const lookup = [
{ value: "Boston Bruins", data: { category: "NHL" } },
{ value: "Boston Celtics", data: { category: "NBA" } },
{ value: "Brooklyn Nets", data: { category: "NBA" } },
{ value: "Buffalo Sabres", data: { category: "NHL" } },
];
const autocomplete = new $.Autocomplete(input, {
lookup,
groupBy: "category",
triggerSelectOnValidInput: false,
});
input.value = "B";
autocomplete.onValueChange();
// NHL came first in lookup, so renders first; within each group,
// original relative order is preserved.
expect(autocomplete.suggestions.map((s) => s.value)).toEqual([
"Boston Bruins",
"Buffalo Sabres",
"Boston Celtics",
"Brooklyn Nets",
]);
});
});
describe("XSS in default formatters (GHSA-hvqh-jw65-wcpq)", () => {
const PAYLOAD = "<img src=x onerror=\"alert('XSS')\">";
afterEach(() => {
$(".autocomplete-suggestions").remove();
});
it("formatGroup escapes the category", () => {
const html = formatGroup({ value: "x", data: null }, PAYLOAD);
expect(html).not.toContain("<img");
expect(html).toContain("<img");
});
it("formatResult escapes the value when currentValue is empty", () => {
const html = formatResult({ value: PAYLOAD, data: null }, "");
expect(html).not.toContain("<img");
expect(html).toContain("<img");
});
it("does not inject DOM nodes when groupBy category is poisoned", () => {
const input = document.createElement("input");
document.body.appendChild(input);
const ac = new $.Autocomplete(input, {
lookup: [
{ value: "Apple", data: { category: PAYLOAD } },
{ value: "Avocado", data: { category: "Safe" } },
],
groupBy: "category",
minChars: 1,
triggerSelectOnValidInput: false,
});
input.value = "A";
ac.onValueChange();
// Poisoned category renders as text inside the group header — no img
// element is created.
const container = ac.suggestionsContainer;
expect(container.querySelectorAll("img").length).toBe(0);
expect(container.querySelector(".autocomplete-group").textContent).toBe(PAYLOAD);
document.body.removeChild(input);
});
});
describe("When options.preserveInput is true", () => {
const input = $("<input />");
let instance;
let suggestionData = null;
beforeEach(() => {
input.autocomplete({
lookup: [
{ value: "Jamaica", data: "J" },
{ value: "Jamaica2", data: "J" },
{ value: "Jamaica3", data: "J" },
],
preserveInput: true,
onSelect: function (suggestion) {
suggestionData = suggestion.data;
},
});
input.val("J");
instance = input.autocomplete();
});
afterEach(() => {
instance.dispose();
});
it("Should NOT change input value when item is selected", () => {
instance.onValueChange();
instance.select(0);
expect(input.val()).toEqual("J");
expect(suggestionData).toBe("J");
});
it("Should NOT change input value when move down", () => {
instance.onValueChange();
instance.moveDown();
expect(input.val()).toEqual("J");
});
it("Should NOT change input value when move up", () => {
instance.onValueChange();
instance.moveUp();
expect(input.val()).toEqual("J");
});
});