summaryrefslogtreecommitdiff
path: root/spec/frontend/pipeline_editor/components/file-nav/branch_switcher_spec.js
blob: d6763a7de41230d476b3d24f9c7a864b4011d059 (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
import {
  GlDropdown,
  GlDropdownItem,
  GlInfiniteScroll,
  GlLoadingIcon,
  GlSearchBoxByType,
} from '@gitlab/ui';
import { createLocalVue, mount, shallowMount } from '@vue/test-utils';
import VueApollo from 'vue-apollo';
import createMockApollo from 'helpers/mock_apollo_helper';
import waitForPromises from 'helpers/wait_for_promises';
import BranchSwitcher from '~/pipeline_editor/components/file_nav/branch_switcher.vue';
import { DEFAULT_FAILURE } from '~/pipeline_editor/constants';
import getAvailableBranches from '~/pipeline_editor/graphql/queries/available_branches.graphql';
import {
  mockBranchPaginationLimit,
  mockDefaultBranch,
  mockEmptySearchBranches,
  mockProjectBranches,
  mockProjectFullPath,
  mockSearchBranches,
  mockTotalBranches,
  mockTotalBranchResults,
  mockTotalSearchResults,
} from '../../mock_data';

const localVue = createLocalVue();
localVue.use(VueApollo);

describe('Pipeline editor branch switcher', () => {
  let wrapper;
  let mockApollo;
  let mockAvailableBranchQuery;

  const createComponent = (
    { isQueryLoading, mountFn, options } = {
      isQueryLoading: false,
      mountFn: shallowMount,
      options: {},
    },
  ) => {
    wrapper = mountFn(BranchSwitcher, {
      propsData: {
        paginationLimit: mockBranchPaginationLimit,
      },
      provide: {
        projectFullPath: mockProjectFullPath,
        totalBranches: mockTotalBranches,
      },
      mocks: {
        $apollo: {
          queries: {
            availableBranches: {
              loading: isQueryLoading,
            },
          },
        },
      },
      data() {
        return {
          branches: ['main'],
          currentBranch: mockDefaultBranch,
        };
      },
      ...options,
    });
  };

  const createComponentWithApollo = (mountFn = shallowMount) => {
    const handlers = [[getAvailableBranches, mockAvailableBranchQuery]];
    mockApollo = createMockApollo(handlers);

    createComponent({
      mountFn,
      options: {
        localVue,
        apolloProvider: mockApollo,
        mocks: {},
        data() {
          return {
            currentBranch: mockDefaultBranch,
          };
        },
      },
    });
  };

  const findDropdown = () => wrapper.findComponent(GlDropdown);
  const findDropdownItems = () => wrapper.findAll(GlDropdownItem);
  const findLoadingIcon = () => wrapper.findComponent(GlLoadingIcon);
  const findSearchBox = () => wrapper.findComponent(GlSearchBoxByType);
  const findInfiniteScroll = () => wrapper.findComponent(GlInfiniteScroll);

  beforeEach(() => {
    mockAvailableBranchQuery = jest.fn();
  });

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

  describe('when querying for the first time', () => {
    beforeEach(() => {
      createComponentWithApollo();
    });

    it('does not render dropdown', () => {
      expect(findDropdown().exists()).toBe(false);
    });
  });

  describe('after querying', () => {
    beforeEach(async () => {
      mockAvailableBranchQuery.mockResolvedValue(mockProjectBranches);
      createComponentWithApollo(mount);
      await waitForPromises();
    });

    it('renders search box', () => {
      expect(findSearchBox().exists()).toBe(true);
    });

    it('renders list of branches', () => {
      expect(findDropdown().exists()).toBe(true);
      expect(findDropdownItems()).toHaveLength(mockTotalBranchResults);
    });

    it('renders current branch with a check mark', () => {
      const defaultBranchInDropdown = findDropdownItems().at(0);

      expect(defaultBranchInDropdown.text()).toBe(mockDefaultBranch);
      expect(defaultBranchInDropdown.props('isChecked')).toBe(true);
    });

    it('does not render check mark for other branches', () => {
      const nonDefaultBranch = findDropdownItems().at(1);

      expect(nonDefaultBranch.text()).not.toBe(mockDefaultBranch);
      expect(nonDefaultBranch.props('isChecked')).toBe(false);
    });
  });

  describe('on fetch error', () => {
    beforeEach(async () => {
      mockAvailableBranchQuery.mockResolvedValue(new Error());
      createComponentWithApollo();
      await waitForPromises();
    });

    it('does not render dropdown', () => {
      expect(findDropdown().exists()).toBe(false);
    });

    it('shows an error message', () => {
      expect(wrapper.emitted('showError')).toBeDefined();
      expect(wrapper.emitted('showError')[0]).toEqual([
        {
          reasons: [wrapper.vm.$options.i18n.fetchError],
          type: DEFAULT_FAILURE,
        },
      ]);
    });
  });

  describe('when switching branches', () => {
    beforeEach(async () => {
      jest.spyOn(window.history, 'pushState').mockImplementation(() => {});
      mockAvailableBranchQuery.mockResolvedValue(mockProjectBranches);
      createComponentWithApollo(mount);
      await waitForPromises();
    });

    it('updates session history when selecting a different branch', async () => {
      const branch = findDropdownItems().at(1);
      await branch.vm.$emit('click');

      expect(window.history.pushState).toHaveBeenCalled();
      expect(window.history.pushState.mock.calls[0][2]).toContain(`?branch_name=${branch.text()}`);
    });

    it('does not update session history when selecting current branch', async () => {
      const branch = findDropdownItems().at(0);
      await branch.vm.$emit('click');

      expect(branch.text()).toBe(mockDefaultBranch);
      expect(window.history.pushState).not.toHaveBeenCalled();
    });

    it('emits the refetchContent event when selecting a different branch', async () => {
      const branch = findDropdownItems().at(1);

      expect(branch.text()).not.toBe(mockDefaultBranch);
      expect(wrapper.emitted('refetchContent')).toBeUndefined();

      await branch.vm.$emit('click');

      expect(wrapper.emitted('refetchContent')).toBeDefined();
      expect(wrapper.emitted('refetchContent')).toHaveLength(1);
    });

    it('does not emit the refetchContent event when selecting the current branch', async () => {
      const branch = findDropdownItems().at(0);

      expect(branch.text()).toBe(mockDefaultBranch);
      expect(wrapper.emitted('refetchContent')).toBeUndefined();

      await branch.vm.$emit('click');

      expect(wrapper.emitted('refetchContent')).toBeUndefined();
    });
  });

  describe('when searching', () => {
    beforeEach(async () => {
      mockAvailableBranchQuery.mockResolvedValue(mockProjectBranches);
      createComponentWithApollo(mount);
      await waitForPromises();

      mockAvailableBranchQuery.mockResolvedValue(mockSearchBranches);
    });

    describe('with a search term', () => {
      it('calls query with correct variables', async () => {
        findSearchBox().vm.$emit('input', 'te');
        await waitForPromises();

        expect(mockAvailableBranchQuery).toHaveBeenCalledWith({
          limit: mockTotalBranches, // fetch all branches
          offset: 0,
          projectFullPath: mockProjectFullPath,
          searchPattern: '*te*',
        });
      });

      it('fetches new list of branches', async () => {
        expect(findDropdownItems()).toHaveLength(mockTotalBranchResults);

        findSearchBox().vm.$emit('input', 'te');
        await waitForPromises();

        expect(findDropdownItems()).toHaveLength(mockTotalSearchResults);
      });

      it('does not hide dropdown when search result is empty', async () => {
        mockAvailableBranchQuery.mockResolvedValue(mockEmptySearchBranches);
        findSearchBox().vm.$emit('input', 'aaaaa');
        await waitForPromises();

        expect(findDropdown().exists()).toBe(true);
        expect(findDropdownItems()).toHaveLength(0);
      });
    });

    describe('without a search term', () => {
      beforeEach(async () => {
        findSearchBox().vm.$emit('input', 'te');
        await waitForPromises();

        mockAvailableBranchQuery.mockResolvedValue(mockProjectBranches);
      });

      it('calls query with correct variables', async () => {
        findSearchBox().vm.$emit('input', '');
        await waitForPromises();

        expect(mockAvailableBranchQuery).toHaveBeenCalledWith({
          limit: mockBranchPaginationLimit, // only fetch first n branches first
          offset: 0,
          projectFullPath: mockProjectFullPath,
          searchPattern: '*',
        });
      });

      it('fetches new list of branches', async () => {
        expect(findDropdownItems()).toHaveLength(mockTotalSearchResults);

        findSearchBox().vm.$emit('input', '');
        await waitForPromises();

        expect(findDropdownItems()).toHaveLength(mockTotalBranchResults);
      });
    });
  });

  describe('loading icon', () => {
    test.each`
      isQueryLoading | isRendered
      ${true}        | ${true}
      ${false}       | ${false}
    `('checks if query is loading before rendering', ({ isQueryLoading, isRendered }) => {
      createComponent({ isQueryLoading, mountFn: mount });

      expect(findLoadingIcon().exists()).toBe(isRendered);
    });
  });

  describe('when scrolling to the bottom of the list', () => {
    beforeEach(async () => {
      mockAvailableBranchQuery.mockResolvedValue(mockProjectBranches);
      createComponentWithApollo();
      await waitForPromises();
    });

    afterEach(() => {
      mockAvailableBranchQuery.mockClear();
    });

    describe('when search term is empty', () => {
      it('fetches more branches', async () => {
        expect(mockAvailableBranchQuery).toHaveBeenCalledTimes(1);

        findInfiniteScroll().vm.$emit('bottomReached');
        await waitForPromises();

        expect(mockAvailableBranchQuery).toHaveBeenCalledTimes(2);
      });

      it('calls the query with the correct variables', async () => {
        findInfiniteScroll().vm.$emit('bottomReached');
        await waitForPromises();

        expect(mockAvailableBranchQuery).toHaveBeenCalledWith({
          limit: mockBranchPaginationLimit,
          offset: mockBranchPaginationLimit, // offset changed
          projectFullPath: mockProjectFullPath,
          searchPattern: '*',
        });
      });
    });

    describe('when search term exists', () => {
      it('does not fetch more branches', async () => {
        findSearchBox().vm.$emit('input', 'te');
        await waitForPromises();

        expect(mockAvailableBranchQuery).toHaveBeenCalledTimes(2);
        mockAvailableBranchQuery.mockClear();

        findInfiniteScroll().vm.$emit('bottomReached');
        await waitForPromises();

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