summaryrefslogtreecommitdiff
path: root/spec/frontend/jira_connect/subscriptions/components/groups_list_spec.js
blob: d3a9a3bfd4118759989dd749c031ddac0d3dc7e3 (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
import { GlAlert, GlLoadingIcon, GlSearchBoxByType, GlPagination } from '@gitlab/ui';
import { shallowMount } from '@vue/test-utils';
import { extendedWrapper } from 'helpers/vue_test_utils_helper';
import waitForPromises from 'helpers/wait_for_promises';
import { fetchGroups } from '~/jira_connect/subscriptions/api';
import GroupsList from '~/jira_connect/subscriptions/components/groups_list.vue';
import GroupsListItem from '~/jira_connect/subscriptions/components/groups_list_item.vue';
import { DEFAULT_GROUPS_PER_PAGE } from '~/jira_connect/subscriptions/constants';
import { mockGroup1, mockGroup2 } from '../mock_data';

const createMockGroup = (groupId) => {
  return {
    ...mockGroup1,
    id: groupId,
  };
};

const createMockGroups = (count) => {
  return [...new Array(count)].map((_, idx) => createMockGroup(idx));
};

jest.mock('~/jira_connect/subscriptions/api', () => {
  return {
    fetchGroups: jest.fn(),
  };
});

const mockGroupsPath = '/groups';

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

  const mockEmptyResponse = { data: [] };

  const createComponent = (options = {}) => {
    wrapper = extendedWrapper(
      shallowMount(GroupsList, {
        provide: {
          groupsPath: mockGroupsPath,
        },
        ...options,
      }),
    );
  };

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

  const findGlAlert = () => wrapper.findComponent(GlAlert);
  const findGlLoadingIcon = () => wrapper.findComponent(GlLoadingIcon);
  const findAllItems = () => wrapper.findAll(GroupsListItem);
  const findFirstItem = () => findAllItems().at(0);
  const findSecondItem = () => findAllItems().at(1);
  const findSearchBox = () => wrapper.findComponent(GlSearchBoxByType);
  const findGroupsList = () => wrapper.findByTestId('groups-list');
  const findPagination = () => wrapper.findComponent(GlPagination);

  describe('when groups are loading', () => {
    it('renders loading icon', async () => {
      fetchGroups.mockReturnValue(new Promise(() => {}));
      createComponent();

      await wrapper.vm.$nextTick();

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

  describe('when groups fetch fails', () => {
    it('renders error message', async () => {
      fetchGroups.mockRejectedValue();
      createComponent();

      await waitForPromises();

      expect(findGlLoadingIcon().exists()).toBe(false);
      expect(findGlAlert().exists()).toBe(true);
      expect(findGlAlert().text()).toBe('Failed to load namespaces. Please try again.');
    });
  });

  describe('with no groups returned', () => {
    it('renders empty state', async () => {
      fetchGroups.mockResolvedValue(mockEmptyResponse);
      createComponent();

      await waitForPromises();

      expect(findGlLoadingIcon().exists()).toBe(false);
      expect(wrapper.text()).toContain('No available namespaces');
    });
  });

  describe('with groups returned', () => {
    beforeEach(async () => {
      fetchGroups.mockResolvedValue({
        headers: { 'X-PAGE': 1, 'X-TOTAL': 2 },
        data: [mockGroup1, mockGroup2],
      });
      createComponent();

      await waitForPromises();
    });

    it('renders groups list', () => {
      expect(findAllItems()).toHaveLength(2);
      expect(findFirstItem().props('group')).toBe(mockGroup1);
      expect(findSecondItem().props('group')).toBe(mockGroup2);
    });

    it('sets GroupListItem `disabled` prop to `false`', () => {
      findAllItems().wrappers.forEach((groupListItem) => {
        expect(groupListItem.props('disabled')).toBe(false);
      });
    });

    it('does not set opacity of the groups list', () => {
      expect(findGroupsList().classes()).not.toContain('gl-opacity-5');
    });

    it('shows error message on $emit from item', async () => {
      const errorMessage = 'error message';

      findFirstItem().vm.$emit('error', errorMessage);

      await wrapper.vm.$nextTick();

      expect(findGlAlert().exists()).toBe(true);
      expect(findGlAlert().text()).toContain(errorMessage);
    });

    describe('when searching groups', () => {
      const mockSearchTeam = 'mock search term';

      describe('while groups are loading', () => {
        beforeEach(async () => {
          fetchGroups.mockClear();
          fetchGroups.mockReturnValue(new Promise(() => {}));

          findSearchBox().vm.$emit('input', mockSearchTeam);
          await wrapper.vm.$nextTick();
        });

        it('calls `fetchGroups` with search term', () => {
          expect(fetchGroups).toHaveBeenLastCalledWith(mockGroupsPath, {
            page: 1,
            perPage: DEFAULT_GROUPS_PER_PAGE,
            search: mockSearchTeam,
          });
        });

        it('disables GroupListItems', () => {
          findAllItems().wrappers.forEach((groupListItem) => {
            expect(groupListItem.props('disabled')).toBe(true);
          });
        });

        it('sets opacity of the groups list', () => {
          expect(findGroupsList().classes()).toContain('gl-opacity-5');
        });

        it('sets loading prop of the search box', () => {
          expect(findSearchBox().props('isLoading')).toBe(true);
        });

        it('sets value prop of the search box to the search term', () => {
          expect(findSearchBox().props('value')).toBe(mockSearchTeam);
        });
      });

      describe('when group search finishes loading', () => {
        beforeEach(async () => {
          fetchGroups.mockResolvedValue({ data: [mockGroup1] });
          findSearchBox().vm.$emit('input');

          await waitForPromises();
        });

        it('renders new groups list', () => {
          expect(findAllItems()).toHaveLength(1);
          expect(findFirstItem().props('group')).toBe(mockGroup1);
        });
      });

      it.each`
        userSearchTerm | finalSearchTerm
        ${'gitl'}      | ${'gitl'}
        ${'git'}       | ${'git'}
        ${'gi'}        | ${''}
        ${'g'}         | ${''}
        ${''}          | ${''}
        ${undefined}   | ${undefined}
      `(
        'searches for "$finalSearchTerm" when user enters "$userSearchTerm"',
        async ({ userSearchTerm, finalSearchTerm }) => {
          fetchGroups.mockResolvedValue({
            data: [mockGroup1],
            headers: { 'X-PAGE': 1, 'X-TOTAL': 1 },
          });

          createComponent();
          await waitForPromises();

          const searchBox = findSearchBox();
          searchBox.vm.$emit('input', userSearchTerm);

          expect(fetchGroups).toHaveBeenLastCalledWith(mockGroupsPath, {
            page: 1,
            perPage: DEFAULT_GROUPS_PER_PAGE,
            search: finalSearchTerm,
          });
        },
      );
    });

    describe('when page=2', () => {
      beforeEach(async () => {
        const totalItems = DEFAULT_GROUPS_PER_PAGE + 1;
        const mockGroups = createMockGroups(totalItems);
        fetchGroups.mockResolvedValue({
          headers: { 'X-TOTAL': totalItems, 'X-PAGE': 1 },
          data: mockGroups,
        });
        createComponent();
        await waitForPromises();

        const paginationEl = findPagination();
        paginationEl.vm.$emit('input', 2);
      });

      it('should load results for page 2', () => {
        expect(fetchGroups).toHaveBeenLastCalledWith(mockGroupsPath, {
          page: 2,
          perPage: DEFAULT_GROUPS_PER_PAGE,
          search: '',
        });
      });

      it('resets page to 1 on search `input` event', () => {
        const mockSearchTerm = 'gitlab';
        const searchBox = findSearchBox();

        searchBox.vm.$emit('input', mockSearchTerm);

        expect(fetchGroups).toHaveBeenLastCalledWith(mockGroupsPath, {
          page: 1,
          perPage: DEFAULT_GROUPS_PER_PAGE,
          search: mockSearchTerm,
        });
      });
    });
  });

  describe('pagination', () => {
    it.each`
      scenario                        | totalItems                     | shouldShowPagination
      ${'renders pagination'}         | ${DEFAULT_GROUPS_PER_PAGE + 1} | ${true}
      ${'does not render pagination'} | ${DEFAULT_GROUPS_PER_PAGE}     | ${false}
      ${'does not render pagination'} | ${2}                           | ${false}
      ${'does not render pagination'} | ${0}                           | ${false}
    `('$scenario with $totalItems groups', async ({ totalItems, shouldShowPagination }) => {
      const mockGroups = createMockGroups(totalItems);
      fetchGroups.mockResolvedValue({
        headers: { 'X-TOTAL': totalItems, 'X-PAGE': 1 },
        data: mockGroups,
      });
      createComponent();
      await waitForPromises();

      const paginationEl = findPagination();

      expect(paginationEl.exists()).toBe(shouldShowPagination);
      if (shouldShowPagination) {
        expect(paginationEl.props('totalItems')).toBe(totalItems);
      }
    });

    describe('when `input` event triggered', () => {
      beforeEach(async () => {
        const MOCK_TOTAL_ITEMS = DEFAULT_GROUPS_PER_PAGE + 1;
        fetchGroups.mockResolvedValue({
          headers: { 'X-TOTAL': MOCK_TOTAL_ITEMS, 'X-PAGE': 1 },
          data: createMockGroups(MOCK_TOTAL_ITEMS),
        });

        createComponent();
        await waitForPromises();
      });

      it('executes `fetchGroups` with correct arguments', () => {
        const paginationEl = findPagination();
        paginationEl.vm.$emit('input', 2);

        expect(fetchGroups).toHaveBeenLastCalledWith(mockGroupsPath, {
          page: 2,
          perPage: DEFAULT_GROUPS_PER_PAGE,
          search: '',
        });
      });
    });
  });
});