summaryrefslogtreecommitdiff
path: root/spec/frontend/header_search/components/app_spec.js
blob: f0de5b083ae476a7da91658befda6ef2619dc14c (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
import { GlSearchBoxByType } from '@gitlab/ui';
import Vue, { nextTick } from 'vue';
import Vuex from 'vuex';
import { shallowMountExtended } from 'helpers/vue_test_utils_helper';
import HeaderSearchApp from '~/header_search/components/app.vue';
import HeaderSearchAutocompleteItems from '~/header_search/components/header_search_autocomplete_items.vue';
import HeaderSearchDefaultItems from '~/header_search/components/header_search_default_items.vue';
import HeaderSearchScopedItems from '~/header_search/components/header_search_scoped_items.vue';
import { SEARCH_INPUT_DESCRIPTION, SEARCH_RESULTS_DESCRIPTION } from '~/header_search/constants';
import DropdownKeyboardNavigation from '~/vue_shared/components/dropdown_keyboard_navigation.vue';
import { ENTER_KEY } from '~/lib/utils/keys';
import { visitUrl } from '~/lib/utils/url_utility';
import {
  MOCK_SEARCH,
  MOCK_SEARCH_QUERY,
  MOCK_USERNAME,
  MOCK_DEFAULT_SEARCH_OPTIONS,
  MOCK_SCOPED_SEARCH_OPTIONS,
  MOCK_SORTED_AUTOCOMPLETE_OPTIONS,
} from '../mock_data';

Vue.use(Vuex);

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

describe('HeaderSearchApp', () => {
  let wrapper;

  const actionSpies = {
    setSearch: jest.fn(),
    fetchAutocompleteOptions: jest.fn(),
    clearAutocomplete: jest.fn(),
  };

  const createComponent = (initialState, mockGetters) => {
    const store = new Vuex.Store({
      state: {
        ...initialState,
      },
      actions: actionSpies,
      getters: {
        searchQuery: () => MOCK_SEARCH_QUERY,
        searchOptions: () => MOCK_DEFAULT_SEARCH_OPTIONS,
        ...mockGetters,
      },
    });

    wrapper = shallowMountExtended(HeaderSearchApp, {
      store,
    });
  };

  afterEach(() => {
    wrapper.destroy();
  });

  const findHeaderSearchInput = () => wrapper.findComponent(GlSearchBoxByType);
  const findHeaderSearchDropdown = () => wrapper.findByTestId('header-search-dropdown-menu');
  const findHeaderSearchDefaultItems = () => wrapper.findComponent(HeaderSearchDefaultItems);
  const findHeaderSearchScopedItems = () => wrapper.findComponent(HeaderSearchScopedItems);
  const findHeaderSearchAutocompleteItems = () =>
    wrapper.findComponent(HeaderSearchAutocompleteItems);
  const findDropdownKeyboardNavigation = () => wrapper.findComponent(DropdownKeyboardNavigation);
  const findSearchInputDescription = () => wrapper.find(`#${SEARCH_INPUT_DESCRIPTION}`);
  const findSearchResultsDescription = () => wrapper.findByTestId(SEARCH_RESULTS_DESCRIPTION);

  describe('template', () => {
    describe('always renders', () => {
      beforeEach(() => {
        createComponent();
      });

      it('Header Search Input', () => {
        expect(findHeaderSearchInput().exists()).toBe(true);
      });

      it('Search Input Description', () => {
        expect(findSearchInputDescription().exists()).toBe(true);
      });

      it('Search Results Description', () => {
        expect(findSearchResultsDescription().exists()).toBe(true);
      });
    });

    describe.each`
      showDropdown | username         | showSearchDropdown
      ${false}     | ${null}          | ${false}
      ${false}     | ${MOCK_USERNAME} | ${false}
      ${true}      | ${null}          | ${false}
      ${true}      | ${MOCK_USERNAME} | ${true}
    `('Header Search Dropdown', ({ showDropdown, username, showSearchDropdown }) => {
      describe(`when showDropdown is ${showDropdown} and current_username is ${username}`, () => {
        beforeEach(() => {
          window.gon.current_username = username;
          createComponent();
          findHeaderSearchInput().vm.$emit(showDropdown ? 'click' : '');
        });

        it(`should${showSearchDropdown ? '' : ' not'} render`, () => {
          expect(findHeaderSearchDropdown().exists()).toBe(showSearchDropdown);
        });
      });
    });

    describe.each`
      search         | showDefault | showScoped | showAutocomplete | showDropdownNavigation
      ${null}        | ${true}     | ${false}   | ${false}         | ${true}
      ${''}          | ${true}     | ${false}   | ${false}         | ${true}
      ${'1'}         | ${false}    | ${false}   | ${false}         | ${false}
      ${')'}         | ${false}    | ${false}   | ${false}         | ${false}
      ${'t'}         | ${false}    | ${false}   | ${true}          | ${true}
      ${'te'}        | ${false}    | ${true}    | ${true}          | ${true}
      ${'tes'}       | ${false}    | ${true}    | ${true}          | ${true}
      ${MOCK_SEARCH} | ${false}    | ${true}    | ${true}          | ${true}
    `(
      'Header Search Dropdown Items',
      ({ search, showDefault, showScoped, showAutocomplete, showDropdownNavigation }) => {
        describe(`when search is ${search}`, () => {
          beforeEach(() => {
            window.gon.current_username = MOCK_USERNAME;
            createComponent(
              { search },
              {
                autocompleteGroupedSearchOptions: () =>
                  search.match(/^[A-Za-z]+$/g) ? MOCK_SORTED_AUTOCOMPLETE_OPTIONS : [],
              },
            );
            findHeaderSearchInput().vm.$emit('click');
          });

          it(`should${showDefault ? '' : ' not'} render the Default Dropdown Items`, () => {
            expect(findHeaderSearchDefaultItems().exists()).toBe(showDefault);
          });

          it(`should${showScoped ? '' : ' not'} render the Scoped Dropdown Items`, () => {
            expect(findHeaderSearchScopedItems().exists()).toBe(showScoped);
          });

          it(`should${
            showAutocomplete ? '' : ' not'
          } render the Autocomplete Dropdown Items`, () => {
            expect(findHeaderSearchAutocompleteItems().exists()).toBe(showAutocomplete);
          });

          it(`should${
            showDropdownNavigation ? '' : ' not'
          } render the Dropdown Navigation Component`, () => {
            expect(findDropdownKeyboardNavigation().exists()).toBe(showDropdownNavigation);
          });
        });
      },
    );

    describe.each`
      username         | showDropdown | expectedDesc
      ${null}          | ${false}     | ${HeaderSearchApp.i18n.searchInputDescribeByNoDropdown}
      ${null}          | ${true}      | ${HeaderSearchApp.i18n.searchInputDescribeByNoDropdown}
      ${MOCK_USERNAME} | ${false}     | ${HeaderSearchApp.i18n.searchInputDescribeByWithDropdown}
      ${MOCK_USERNAME} | ${true}      | ${HeaderSearchApp.i18n.searchInputDescribeByWithDropdown}
    `('Search Input Description', ({ username, showDropdown, expectedDesc }) => {
      describe(`current_username is ${username} and showDropdown is ${showDropdown}`, () => {
        beforeEach(() => {
          window.gon.current_username = username;
          createComponent();
          findHeaderSearchInput().vm.$emit(showDropdown ? 'click' : '');
        });

        it(`sets description to ${expectedDesc}`, () => {
          expect(findSearchInputDescription().text()).toBe(expectedDesc);
        });
      });
    });

    describe.each`
      username         | showDropdown | search         | loading  | searchOptions                  | expectedDesc
      ${null}          | ${true}      | ${''}          | ${false} | ${[]}                          | ${''}
      ${MOCK_USERNAME} | ${false}     | ${''}          | ${false} | ${[]}                          | ${''}
      ${MOCK_USERNAME} | ${true}      | ${''}          | ${false} | ${MOCK_DEFAULT_SEARCH_OPTIONS} | ${`${MOCK_DEFAULT_SEARCH_OPTIONS.length} default results provided. Use the up and down arrow keys to navigate search results list.`}
      ${MOCK_USERNAME} | ${true}      | ${''}          | ${true}  | ${MOCK_DEFAULT_SEARCH_OPTIONS} | ${`${MOCK_DEFAULT_SEARCH_OPTIONS.length} default results provided. Use the up and down arrow keys to navigate search results list.`}
      ${MOCK_USERNAME} | ${true}      | ${MOCK_SEARCH} | ${false} | ${MOCK_SCOPED_SEARCH_OPTIONS}  | ${`Results updated. ${MOCK_SCOPED_SEARCH_OPTIONS.length} results available. Use the up and down arrow keys to navigate search results list, or ENTER to submit.`}
      ${MOCK_USERNAME} | ${true}      | ${MOCK_SEARCH} | ${true}  | ${MOCK_SCOPED_SEARCH_OPTIONS}  | ${HeaderSearchApp.i18n.searchResultsLoading}
    `(
      'Search Results Description',
      ({ username, showDropdown, search, loading, searchOptions, expectedDesc }) => {
        describe(`search is ${search}, loading is ${loading}, and showSearchDropdown is ${
          Boolean(username) && showDropdown
        }`, () => {
          beforeEach(() => {
            window.gon.current_username = username;
            createComponent({ search, loading }, { searchOptions: () => searchOptions });
            findHeaderSearchInput().vm.$emit(showDropdown ? 'click' : '');
          });

          it(`sets description to ${expectedDesc}`, () => {
            expect(findSearchResultsDescription().text()).toBe(expectedDesc);
          });
        });
      },
    );
  });

  describe('events', () => {
    beforeEach(() => {
      createComponent();
      window.gon.current_username = MOCK_USERNAME;
    });

    describe('Header Search Input', () => {
      describe('when dropdown is closed', () => {
        it('onFocus opens dropdown', async () => {
          expect(findHeaderSearchDropdown().exists()).toBe(false);
          findHeaderSearchInput().vm.$emit('focus');

          await nextTick();

          expect(findHeaderSearchDropdown().exists()).toBe(true);
        });

        it('onClick opens dropdown', async () => {
          expect(findHeaderSearchDropdown().exists()).toBe(false);
          findHeaderSearchInput().vm.$emit('click');

          await nextTick();

          expect(findHeaderSearchDropdown().exists()).toBe(true);
        });
      });

      describe('onInput', () => {
        describe('when search has text', () => {
          beforeEach(() => {
            findHeaderSearchInput().vm.$emit('input', MOCK_SEARCH);
          });

          it('calls setSearch with search term', () => {
            expect(actionSpies.setSearch).toHaveBeenCalledWith(expect.any(Object), MOCK_SEARCH);
          });

          it('calls fetchAutocompleteOptions', () => {
            expect(actionSpies.fetchAutocompleteOptions).toHaveBeenCalled();
          });

          it('does not call clearAutocomplete', () => {
            expect(actionSpies.clearAutocomplete).not.toHaveBeenCalled();
          });
        });

        describe('when search is emptied', () => {
          beforeEach(() => {
            findHeaderSearchInput().vm.$emit('input', '');
          });

          it('calls setSearch with empty term', () => {
            expect(actionSpies.setSearch).toHaveBeenCalledWith(expect.any(Object), '');
          });

          it('does not call fetchAutocompleteOptions', () => {
            expect(actionSpies.fetchAutocompleteOptions).not.toHaveBeenCalled();
          });

          it('calls clearAutocomplete', () => {
            expect(actionSpies.clearAutocomplete).toHaveBeenCalled();
          });
        });
      });
    });

    describe('Dropdown Keyboard Navigation', () => {
      beforeEach(() => {
        findHeaderSearchInput().vm.$emit('click');
      });

      it('closes dropdown when @tab is emitted', async () => {
        expect(findHeaderSearchDropdown().exists()).toBe(true);
        findDropdownKeyboardNavigation().vm.$emit('tab');

        await nextTick();

        expect(findHeaderSearchDropdown().exists()).toBe(false);
      });
    });
  });

  describe('computed', () => {
    describe('currentFocusedOption', () => {
      const MOCK_INDEX = 1;

      beforeEach(() => {
        createComponent();
        window.gon.current_username = MOCK_USERNAME;
        findHeaderSearchInput().vm.$emit('click');
      });

      it(`when currentFocusIndex changes to ${MOCK_INDEX} updates the data to searchOptions[${MOCK_INDEX}]`, async () => {
        findDropdownKeyboardNavigation().vm.$emit('change', MOCK_INDEX);
        await nextTick();
        expect(wrapper.vm.currentFocusedOption).toBe(MOCK_DEFAULT_SEARCH_OPTIONS[MOCK_INDEX]);
      });
    });
  });

  describe('Submitting a search', () => {
    describe('with no currentFocusedOption', () => {
      beforeEach(() => {
        createComponent();
      });

      it('onKey-enter submits a search', async () => {
        findHeaderSearchInput().vm.$emit('keydown', new KeyboardEvent({ key: ENTER_KEY }));

        await nextTick();

        expect(visitUrl).toHaveBeenCalledWith(MOCK_SEARCH_QUERY);
      });
    });

    describe('with currentFocusedOption', () => {
      const MOCK_INDEX = 1;

      beforeEach(() => {
        createComponent();
        window.gon.current_username = MOCK_USERNAME;
        findHeaderSearchInput().vm.$emit('click');
      });

      it('onKey-enter clicks the selected dropdown item rather than submitting a search', async () => {
        findDropdownKeyboardNavigation().vm.$emit('change', MOCK_INDEX);
        await nextTick();
        findHeaderSearchInput().vm.$emit('keydown', new KeyboardEvent({ key: ENTER_KEY }));
        expect(visitUrl).toHaveBeenCalledWith(MOCK_DEFAULT_SEARCH_OPTIONS[MOCK_INDEX].url);
      });
    });
  });
});