summaryrefslogtreecommitdiff
path: root/spec/frontend/filtered_search/filtered_search_manager_spec.js
blob: 911a507af4c16eb1a92e86d9d2814baf234d520a (plain)
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
import FilteredSearchManager from 'ee_else_ce/filtered_search/filtered_search_manager';

import FilteredSearchSpecHelper from 'helpers/filtered_search_spec_helper';
import DropdownUtils from '~/filtered_search/dropdown_utils';
import FilteredSearchDropdownManager from '~/filtered_search/filtered_search_dropdown_manager';
import FilteredSearchVisualTokens from '~/filtered_search/filtered_search_visual_tokens';
import IssuableFilteredSearchTokenKeys from '~/filtered_search/issuable_filtered_search_token_keys';
import RecentSearchesRoot from '~/filtered_search/recent_searches_root';
import RecentSearchesService from '~/filtered_search/services/recent_searches_service';
import RecentSearchesServiceError from '~/filtered_search/services/recent_searches_service_error';
import createFlash from '~/flash';
import { BACKSPACE_KEY_CODE, DELETE_KEY_CODE } from '~/lib/utils/keycodes';
import { visitUrl, getParameterByName } from '~/lib/utils/url_utility';

jest.mock('~/flash');
jest.mock('~/lib/utils/url_utility', () => ({
  ...jest.requireActual('~/lib/utils/url_utility'),
  getParameterByName: jest.fn(),
  visitUrl: jest.fn(),
}));

describe('Filtered Search Manager', () => {
  let input;
  let manager;
  let tokensContainer;
  const page = 'issues';
  const placeholder = 'Search or filter results...';

  function dispatchBackspaceEvent(element, eventType) {
    const event = new Event(eventType);
    event.keyCode = BACKSPACE_KEY_CODE;
    element.dispatchEvent(event);
  }

  function dispatchDeleteEvent(element, eventType) {
    const event = new Event(eventType);
    event.keyCode = DELETE_KEY_CODE;
    element.dispatchEvent(event);
  }

  function dispatchAltBackspaceEvent(element, eventType) {
    const event = new Event(eventType);
    event.altKey = true;
    event.keyCode = BACKSPACE_KEY_CODE;
    element.dispatchEvent(event);
  }

  function dispatchCtrlBackspaceEvent(element, eventType) {
    const event = new Event(eventType);
    event.ctrlKey = true;
    event.keyCode = BACKSPACE_KEY_CODE;
    element.dispatchEvent(event);
  }

  function dispatchMetaBackspaceEvent(element, eventType) {
    const event = new Event(eventType);
    event.metaKey = true;
    event.keyCode = BACKSPACE_KEY_CODE;
    element.dispatchEvent(event);
  }

  function getVisualTokens() {
    return tokensContainer.querySelectorAll('.js-visual-token');
  }

  beforeEach(() => {
    setFixtures(`
      <div class="filtered-search-box">
        <form>
          <ul class="tokens-container list-unstyled">
            ${FilteredSearchSpecHelper.createInputHTML(placeholder)}
          </ul>
          <button class="clear-search" type="button">
            <svg class="s16 clear-search-icon" data-testid="close-icon"><use xlink:href="icons.svg#close" /></svg>
          </button>
        </form>
      </div>
    `);

    jest.spyOn(FilteredSearchDropdownManager.prototype, 'setDropdown').mockImplementation();
  });

  const initializeManager = ({ useDefaultState } = {}) => {
    jest.spyOn(FilteredSearchManager.prototype, 'loadSearchParamsFromURL').mockImplementation();
    jest.spyOn(FilteredSearchManager.prototype, 'tokenChange').mockImplementation();
    jest
      .spyOn(FilteredSearchDropdownManager.prototype, 'updateDropdownOffset')
      .mockImplementation();
    jest.spyOn(FilteredSearchVisualTokens, 'unselectTokens');

    getParameterByName.mockReturnValue(null);

    input = document.querySelector('.filtered-search');
    tokensContainer = document.querySelector('.tokens-container');
    manager = new FilteredSearchManager({ page, useDefaultState });
    manager.setup();
  };

  afterEach(() => {
    manager.cleanup();
  });

  describe('class constructor', () => {
    const isLocalStorageAvailable = 'isLocalStorageAvailable';

    beforeEach(() => {
      jest.spyOn(RecentSearchesService, 'isAvailable').mockReturnValue(isLocalStorageAvailable);
      jest.spyOn(RecentSearchesRoot.prototype, 'render').mockImplementation();
    });

    it('should instantiate RecentSearchesStore with isLocalStorageAvailable', () => {
      manager = new FilteredSearchManager({ page });

      expect(RecentSearchesService.isAvailable).toHaveBeenCalled();
      expect(manager.recentSearchesStore.state).toEqual(
        expect.objectContaining({
          isLocalStorageAvailable,
          allowedKeys: IssuableFilteredSearchTokenKeys.getKeys(),
        }),
      );
    });
  });

  describe('setup', () => {
    beforeEach(() => {
      manager = new FilteredSearchManager({ page });
    });

    it('should not instantiate Flash if an RecentSearchesServiceError is caught', () => {
      jest
        .spyOn(RecentSearchesService.prototype, 'fetch')
        .mockImplementation(() => Promise.reject(new RecentSearchesServiceError()));

      manager.setup();

      expect(createFlash).not.toHaveBeenCalled();
    });
  });

  describe('searchState', () => {
    beforeEach(() => {
      jest.spyOn(FilteredSearchManager.prototype, 'search').mockImplementation();
      initializeManager();
    });

    it('should blur button', () => {
      const e = {
        preventDefault: () => {},
        currentTarget: {
          blur: () => {},
        },
      };
      jest.spyOn(e.currentTarget, 'blur');
      manager.searchState(e);

      expect(e.currentTarget.blur).toHaveBeenCalled();
    });

    it('should not call search if there is no state', () => {
      const e = {
        preventDefault: () => {},
        currentTarget: {
          blur: () => {},
        },
      };

      manager.searchState(e);

      expect(FilteredSearchManager.prototype.search).not.toHaveBeenCalled();
    });

    it('should call search when there is state', () => {
      const e = {
        preventDefault: () => {},
        currentTarget: {
          blur: () => {},
          dataset: {
            state: 'opened',
          },
        },
      };

      manager.searchState(e);

      expect(FilteredSearchManager.prototype.search).toHaveBeenCalledWith('opened');
    });
  });

  describe('search', () => {
    const defaultParams = '?scope=all';
    const defaultState = '&state=opened';

    it('should search with a single word', () => {
      initializeManager();
      input.value = 'searchTerm';

      visitUrl.mockImplementation((url) => {
        expect(url).toEqual(`${defaultParams}&search=searchTerm`);
      });

      manager.search();
    });

    it('sets default state', () => {
      initializeManager({ useDefaultState: true });
      input.value = 'searchTerm';

      visitUrl.mockImplementation((url) => {
        expect(url).toEqual(`${defaultParams}${defaultState}&search=searchTerm`);
      });

      manager.search();
    });

    it('should search with multiple words', () => {
      initializeManager();
      input.value = 'awesome search terms';

      visitUrl.mockImplementation((url) => {
        expect(url).toEqual(`${defaultParams}&search=awesome+search+terms`);
      });

      manager.search();
    });

    it('should search with special characters', () => {
      initializeManager();
      input.value = '~!@#$%^&*()_+{}:<>,.?/';

      visitUrl.mockImplementation((url) => {
        expect(url).toEqual(
          `${defaultParams}&search=~!%40%23%24%25%5E%26*()_%2B%7B%7D%3A%3C%3E%2C.%3F%2F`,
        );
      });

      manager.search();
    });

    it('should use replacement URL for condition', () => {
      initializeManager();
      tokensContainer.innerHTML = FilteredSearchSpecHelper.createTokensContainerHTML(
        FilteredSearchSpecHelper.createFilterVisualTokenHTML('milestone', '=', '13', true),
      );

      visitUrl.mockImplementation((url) => {
        expect(url).toEqual(`${defaultParams}&milestone_title=replaced`);
      });

      manager.filteredSearchTokenKeys.conditions.push({
        url: 'milestone_title=13',
        replacementUrl: 'milestone_title=replaced',
        tokenKey: 'milestone',
        value: '13',
        operator: '=',
      });
      manager.search();
    });

    it('removes duplicated tokens', () => {
      initializeManager();
      tokensContainer.innerHTML = FilteredSearchSpecHelper.createTokensContainerHTML(`
        ${FilteredSearchSpecHelper.createFilterVisualTokenHTML('label', '=', '~bug')}
        ${FilteredSearchSpecHelper.createFilterVisualTokenHTML('label', '=', '~bug')}
      `);

      visitUrl.mockImplementation((url) => {
        expect(url).toEqual(`${defaultParams}&label_name[]=bug`);
      });

      manager.search();
    });
  });

  describe('handleInputPlaceholder', () => {
    beforeEach(() => {
      initializeManager();
    });

    it('should render placeholder when there is no input', () => {
      expect(input.placeholder).toEqual(placeholder);
    });

    it('should not render placeholder when there is input', () => {
      input.value = 'test words';

      const event = new Event('input');
      input.dispatchEvent(event);

      expect(input.placeholder).toEqual('');
    });

    it('should not render placeholder when there are tokens and no input', () => {
      tokensContainer.innerHTML = FilteredSearchSpecHelper.createTokensContainerHTML(
        FilteredSearchSpecHelper.createFilterVisualTokenHTML('label', '=', '~bug'),
      );

      const event = new Event('input');
      input.dispatchEvent(event);

      expect(input.placeholder).toEqual('');
    });
  });

  describe('checkForBackspace', () => {
    beforeEach(() => {
      initializeManager();
    });

    describe('tokens and no input', () => {
      beforeEach(() => {
        tokensContainer.innerHTML = FilteredSearchSpecHelper.createTokensContainerHTML(
          FilteredSearchSpecHelper.createFilterVisualTokenHTML('label', '=', '~bug'),
        );
      });

      it('removes last token', () => {
        jest.spyOn(FilteredSearchVisualTokens, 'removeLastTokenPartial');
        dispatchBackspaceEvent(input, 'keyup');
        dispatchBackspaceEvent(input, 'keyup');

        expect(FilteredSearchVisualTokens.removeLastTokenPartial).toHaveBeenCalled();
      });

      it('sets the input', () => {
        jest.spyOn(FilteredSearchVisualTokens, 'getLastTokenPartial');
        dispatchDeleteEvent(input, 'keyup');
        dispatchDeleteEvent(input, 'keyup');

        expect(FilteredSearchVisualTokens.getLastTokenPartial).toHaveBeenCalled();
        expect(input.value).toEqual('~bug');
      });
    });

    it('does not remove token or change input when there is existing input', () => {
      jest.spyOn(FilteredSearchVisualTokens, 'removeLastTokenPartial');
      jest.spyOn(FilteredSearchVisualTokens, 'getLastTokenPartial');

      input.value = 'text';
      dispatchDeleteEvent(input, 'keyup');

      expect(FilteredSearchVisualTokens.removeLastTokenPartial).not.toHaveBeenCalled();
      expect(FilteredSearchVisualTokens.getLastTokenPartial).not.toHaveBeenCalled();
      expect(input.value).toEqual('text');
    });

    it('does not remove previous token on single backspace press', () => {
      jest.spyOn(FilteredSearchVisualTokens, 'removeLastTokenPartial');
      jest.spyOn(FilteredSearchVisualTokens, 'getLastTokenPartial');

      input.value = 't';
      dispatchDeleteEvent(input, 'keyup');

      expect(FilteredSearchVisualTokens.removeLastTokenPartial).not.toHaveBeenCalled();
      expect(FilteredSearchVisualTokens.getLastTokenPartial).not.toHaveBeenCalled();
      expect(input.value).toEqual('t');
    });
  });

  describe('checkForAltOrCtrlBackspace', () => {
    beforeEach(() => {
      initializeManager();
      jest.spyOn(FilteredSearchVisualTokens, 'removeLastTokenPartial');
    });

    describe('tokens and no input', () => {
      beforeEach(() => {
        tokensContainer.innerHTML = FilteredSearchSpecHelper.createTokensContainerHTML(
          FilteredSearchSpecHelper.createFilterVisualTokenHTML('label', '=', '~bug'),
        );
      });

      it('removes last token via alt-backspace', () => {
        dispatchAltBackspaceEvent(input, 'keydown');

        expect(FilteredSearchVisualTokens.removeLastTokenPartial).toHaveBeenCalled();
      });

      it('removes last token via ctrl-backspace', () => {
        dispatchCtrlBackspaceEvent(input, 'keydown');

        expect(FilteredSearchVisualTokens.removeLastTokenPartial).toHaveBeenCalled();
      });
    });

    describe('tokens and input', () => {
      beforeEach(() => {
        tokensContainer.innerHTML = FilteredSearchSpecHelper.createTokensContainerHTML(
          FilteredSearchSpecHelper.createFilterVisualTokenHTML('label', '=', '~bug'),
        );
      });

      it('does not remove token or change input via alt-backspace when there is existing input', () => {
        input = manager.filteredSearchInput;
        input.value = 'text';
        dispatchAltBackspaceEvent(input, 'keydown');

        expect(FilteredSearchVisualTokens.removeLastTokenPartial).not.toHaveBeenCalled();
        expect(input.value).toEqual('text');
      });

      it('does not remove token or change input via ctrl-backspace when there is existing input', () => {
        input = manager.filteredSearchInput;
        input.value = 'text';
        dispatchCtrlBackspaceEvent(input, 'keydown');

        expect(FilteredSearchVisualTokens.removeLastTokenPartial).not.toHaveBeenCalled();
        expect(input.value).toEqual('text');
      });
    });
  });

  describe('checkForMetaBackspace', () => {
    beforeEach(() => {
      initializeManager();
    });

    beforeEach(() => {
      tokensContainer.innerHTML = FilteredSearchSpecHelper.createTokensContainerHTML(
        FilteredSearchSpecHelper.createFilterVisualTokenHTML('label', '=', '~bug'),
      );
    });

    it('removes all tokens and input', () => {
      jest.spyOn(FilteredSearchManager.prototype, 'clearSearch');
      dispatchMetaBackspaceEvent(input, 'keydown');

      expect(manager.clearSearch).toHaveBeenCalled();
      expect(manager.filteredSearchInput.value).toEqual('');
      expect(DropdownUtils.getSearchQuery()).toEqual('');
    });
  });

  describe('removeToken', () => {
    beforeEach(() => {
      initializeManager();
    });

    it('removes token even when it is already selected', () => {
      tokensContainer.innerHTML = FilteredSearchSpecHelper.createTokensContainerHTML(
        FilteredSearchSpecHelper.createFilterVisualTokenHTML('milestone', '=', 'none', true),
      );

      tokensContainer.querySelector('.js-visual-token .remove-token').click();

      expect(tokensContainer.querySelector('.js-visual-token')).toEqual(null);
    });

    describe('unselected token', () => {
      beforeEach(() => {
        jest.spyOn(FilteredSearchManager.prototype, 'removeSelectedToken');

        tokensContainer.innerHTML = FilteredSearchSpecHelper.createTokensContainerHTML(
          FilteredSearchSpecHelper.createFilterVisualTokenHTML('milestone', '=', 'none'),
        );
        tokensContainer.querySelector('.js-visual-token .remove-token').click();
      });

      it('removes token when remove button is selected', () => {
        expect(tokensContainer.querySelector('.js-visual-token')).toEqual(null);
      });

      it('calls removeSelectedToken', () => {
        expect(manager.removeSelectedToken).toHaveBeenCalled();
      });
    });
  });

  describe('removeSelectedTokenKeydown', () => {
    beforeEach(() => {
      initializeManager();
      tokensContainer.innerHTML = FilteredSearchSpecHelper.createTokensContainerHTML(
        FilteredSearchSpecHelper.createFilterVisualTokenHTML('milestone', '=', 'none', true),
      );
    });

    it('removes selected token when the backspace key is pressed', () => {
      expect(getVisualTokens().length).toEqual(1);

      dispatchBackspaceEvent(document, 'keydown');

      expect(getVisualTokens().length).toEqual(0);
    });

    it('removes selected token when the delete key is pressed', () => {
      expect(getVisualTokens().length).toEqual(1);

      dispatchDeleteEvent(document, 'keydown');

      expect(getVisualTokens().length).toEqual(0);
    });

    it('updates the input placeholder after removal', () => {
      manager.handleInputPlaceholder();

      expect(input.placeholder).toEqual('');
      expect(getVisualTokens().length).toEqual(1);

      dispatchBackspaceEvent(document, 'keydown');

      expect(input.placeholder).not.toEqual('');
      expect(getVisualTokens().length).toEqual(0);
    });

    it('updates the clear button after removal', () => {
      manager.toggleClearSearchButton();

      const clearButton = document.querySelector('.clear-search');

      expect(clearButton.classList.contains('hidden')).toEqual(false);
      expect(getVisualTokens().length).toEqual(1);

      dispatchBackspaceEvent(document, 'keydown');

      expect(clearButton.classList.contains('hidden')).toEqual(true);
      expect(getVisualTokens().length).toEqual(0);
    });
  });

  describe('removeSelectedToken', () => {
    beforeEach(() => {
      jest.spyOn(FilteredSearchVisualTokens, 'removeSelectedToken');
      jest.spyOn(FilteredSearchManager.prototype, 'handleInputPlaceholder');
      jest.spyOn(FilteredSearchManager.prototype, 'toggleClearSearchButton');
      initializeManager();
    });

    it('calls FilteredSearchVisualTokens.removeSelectedToken', () => {
      manager.removeSelectedToken();

      expect(FilteredSearchVisualTokens.removeSelectedToken).toHaveBeenCalled();
    });

    it('calls handleInputPlaceholder', () => {
      manager.removeSelectedToken();

      expect(manager.handleInputPlaceholder).toHaveBeenCalled();
    });

    it('calls toggleClearSearchButton', () => {
      manager.removeSelectedToken();

      expect(manager.toggleClearSearchButton).toHaveBeenCalled();
    });

    it('calls update dropdown offset', () => {
      manager.removeSelectedToken();

      expect(manager.dropdownManager.updateDropdownOffset).toHaveBeenCalled();
    });
  });

  describe('Clearing search', () => {
    beforeEach(() => {
      initializeManager();
    });

    it('Clicking the "x" clear button, clears the input', () => {
      const inputValue = 'label:=~bug';
      manager.filteredSearchInput.value = inputValue;
      manager.filteredSearchInput.dispatchEvent(new Event('input'));

      expect(DropdownUtils.getSearchQuery()).toEqual(inputValue);

      manager.clearSearchButton.click();

      expect(manager.filteredSearchInput.value).toEqual('');
      expect(DropdownUtils.getSearchQuery()).toEqual('');
    });
  });

  describe('toggleInputContainerFocus', () => {
    beforeEach(() => {
      initializeManager();
    });

    it('toggles on focus', () => {
      input.focus();

      expect(document.querySelector('.filtered-search-box').classList.contains('focus')).toEqual(
        true,
      );
    });

    it('toggles on blur', () => {
      input.blur();

      expect(document.querySelector('.filtered-search-box').classList.contains('focus')).toEqual(
        false,
      );
    });
  });

  describe('getAllParams', () => {
    let paramsArr;
    beforeEach(() => {
      paramsArr = ['key=value', 'otherkey=othervalue'];

      initializeManager();
    });

    it('correctly modifies params when custom modifier is passed', () => {
      const modifedParams = manager.getAllParams.call(
        {
          modifyUrlParams: (params) => params.reverse(),
        },
        [].concat(paramsArr),
      );

      expect(modifedParams[0]).toBe(paramsArr[1]);
    });

    it('does not modify params when no custom modifier is passed', () => {
      const modifedParams = manager.getAllParams.call({}, paramsArr);

      expect(modifedParams[1]).toBe(paramsArr[1]);
    });
  });
});