Welcome to mirror list, hosted at ThFree Co, Russian Federation.

issues_dashboard_app_spec.js « components « dashboard « issues « frontend « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 148c6230b9f6a440d8ffbbb3ffda6c51a53b06fe (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
import { GlDisclosureDropdown, GlEmptyState } from '@gitlab/ui';
import * as Sentry from '@sentry/browser';
import AxiosMockAdapter from 'axios-mock-adapter';
import Vue, { nextTick } from 'vue';
import VueApollo from 'vue-apollo';
import { cloneDeep } from 'lodash';
import getIssuesQuery from 'ee_else_ce/issues/dashboard/queries/get_issues.query.graphql';
import IssueCardStatistics from 'ee_else_ce/issues/list/components/issue_card_statistics.vue';
import IssueCardTimeInfo from 'ee_else_ce/issues/list/components/issue_card_time_info.vue';
import createMockApollo from 'helpers/mock_apollo_helper';
import setWindowLocation from 'helpers/set_window_location_helper';
import { TEST_HOST } from 'helpers/test_constants';
import { mountExtended } from 'helpers/vue_test_utils_helper';
import waitForPromises from 'helpers/wait_for_promises';
import {
  filteredTokens,
  locationSearch,
  setSortPreferenceMutationResponse,
  setSortPreferenceMutationResponseWithErrors,
} from 'jest/issues/list/mock_data';
import { STATUS_ALL, STATUS_CLOSED, STATUS_OPEN } from '~/issues/constants';
import IssuesDashboardApp from '~/issues/dashboard/components/issues_dashboard_app.vue';
import getIssuesCountsQuery from '~/issues/dashboard/queries/get_issues_counts.query.graphql';
import { CREATED_DESC, i18n, UPDATED_DESC, urlSortParams } from '~/issues/list/constants';
import setSortPreferenceMutation from '~/issues/list/queries/set_sort_preference.mutation.graphql';
import { getSortKey, getSortOptions } from '~/issues/list/utils';
import axios from '~/lib/utils/axios_utils';
import { scrollUp } from '~/lib/utils/scroll_utils';
import {
  TOKEN_TYPE_ASSIGNEE,
  TOKEN_TYPE_AUTHOR,
  TOKEN_TYPE_CONFIDENTIAL,
  TOKEN_TYPE_LABEL,
  TOKEN_TYPE_MILESTONE,
  TOKEN_TYPE_MY_REACTION,
  TOKEN_TYPE_SEARCH_WITHIN,
  TOKEN_TYPE_TYPE,
} from '~/vue_shared/components/filtered_search_bar/constants';
import IssuableList from '~/vue_shared/issuable/list/components/issuable_list_root.vue';
import {
  emptyIssuesQueryResponse,
  issuesCountsQueryResponse,
  issuesQueryResponse,
} from '../mock_data';

jest.mock('@sentry/browser');
jest.mock('~/lib/utils/scroll_utils', () => ({ scrollUp: jest.fn() }));

describe('IssuesDashboardApp component', () => {
  let axiosMock;
  let wrapper;

  Vue.use(VueApollo);

  const defaultProvide = {
    autocompleteAwardEmojisPath: 'autocomplete/award/emojis/path',
    autocompleteUsersPath: 'autocomplete/users.json',
    calendarPath: 'calendar/path',
    dashboardLabelsPath: 'dashboard/labels/path',
    dashboardMilestonesPath: 'dashboard/milestones/path',
    emptyStateWithFilterSvgPath: 'empty/state/with/filter/svg/path.svg',
    emptyStateWithoutFilterSvgPath: 'empty/state/with/filter/svg/path.svg',
    hasBlockedIssuesFeature: true,
    hasIssuableHealthStatusFeature: true,
    hasIssueWeightsFeature: true,
    hasScopedLabelsFeature: true,
    initialSort: CREATED_DESC,
    isPublicVisibilityRestricted: false,
    isSignedIn: true,
    rssPath: 'rss/path',
  };

  let defaultQueryResponse = issuesQueryResponse;
  if (IS_EE) {
    defaultQueryResponse = cloneDeep(issuesQueryResponse);
    defaultQueryResponse.data.issues.nodes[0].blockingCount = 1;
    defaultQueryResponse.data.issues.nodes[0].healthStatus = null;
    defaultQueryResponse.data.issues.nodes[0].weight = 5;
  }

  const findCalendarButton = () => wrapper.findByRole('link', { name: i18n.calendarLabel });
  const findDisclosureDropdown = () => wrapper.findComponent(GlDisclosureDropdown);
  const findEmptyState = () => wrapper.findComponent(GlEmptyState);
  const findIssuableList = () => wrapper.findComponent(IssuableList);
  const findIssueCardStatistics = () => wrapper.findComponent(IssueCardStatistics);
  const findIssueCardTimeInfo = () => wrapper.findComponent(IssueCardTimeInfo);
  const findRssButton = () => wrapper.findByRole('link', { name: i18n.rssLabel });

  const mountComponent = ({
    provide = {},
    issuesQueryHandler = jest.fn().mockResolvedValue(defaultQueryResponse),
    issuesCountsQueryHandler = jest.fn().mockResolvedValue(issuesCountsQueryResponse),
    sortPreferenceMutationHandler = jest.fn().mockResolvedValue(setSortPreferenceMutationResponse),
  } = {}) => {
    wrapper = mountExtended(IssuesDashboardApp, {
      apolloProvider: createMockApollo([
        [getIssuesQuery, issuesQueryHandler],
        [getIssuesCountsQuery, issuesCountsQueryHandler],
        [setSortPreferenceMutation, sortPreferenceMutationHandler],
      ]),
      provide: {
        ...defaultProvide,
        ...provide,
      },
    });
  };

  beforeEach(() => {
    setWindowLocation(TEST_HOST);
    axiosMock = new AxiosMockAdapter(axios);
  });

  afterEach(() => {
    axiosMock.reset();
  });

  describe('UI components', () => {
    beforeEach(async () => {
      setWindowLocation(locationSearch);
      mountComponent();
      await waitForPromises();
    });

    // quarantine: https://gitlab.com/gitlab-org/gitlab/-/issues/391722
    // eslint-disable-next-line jest/no-disabled-tests
    it.skip('renders IssuableList component', () => {
      expect(findIssuableList().props()).toMatchObject({
        currentTab: STATUS_OPEN,
        hasNextPage: true,
        hasPreviousPage: false,
        hasScopedLabelsFeature: defaultProvide.hasScopedLabelsFeature,
        initialSortBy: CREATED_DESC,
        issuables: issuesQueryResponse.data.issues.nodes,
        issuablesLoading: false,
        namespace: 'dashboard',
        recentSearchesStorageKey: 'issues',
        searchInputPlaceholder: i18n.searchPlaceholder,
        showPaginationControls: true,
        sortOptions: getSortOptions({
          hasBlockedIssuesFeature: defaultProvide.hasBlockedIssuesFeature,
          hasIssuableHealthStatusFeature: defaultProvide.hasIssuableHealthStatusFeature,
          hasIssueWeightsFeature: defaultProvide.hasIssueWeightsFeature,
        }),
        tabCounts: {
          opened: 1,
          closed: 2,
          all: 3,
        },
        tabs: IssuesDashboardApp.issuableListTabs,
        urlParams: {
          sort: urlSortParams[CREATED_DESC],
          state: STATUS_OPEN,
        },
        useKeysetPagination: true,
      });
    });

    describe('actions dropdown', () => {
      it('renders', () => {
        expect(findDisclosureDropdown().props()).toMatchObject({
          category: 'tertiary',
          icon: 'ellipsis_v',
          noCaret: true,
          textSrOnly: true,
          toggleText: 'Actions',
        });
      });

      it('renders RSS button link', () => {
        expect(findRssButton().attributes('href')).toBe(defaultProvide.rssPath);
      });

      it('renders calendar button link', () => {
        expect(findCalendarButton().attributes('href')).toBe(defaultProvide.calendarPath);
      });
    });

    it('renders issue time information', () => {
      expect(findIssueCardTimeInfo().exists()).toBe(true);
    });

    it('renders issue statistics', () => {
      expect(findIssueCardStatistics().exists()).toBe(true);
    });
  });

  describe('fetching issues', () => {
    describe('with a search query', () => {
      describe('when there are issues returned', () => {
        beforeEach(async () => {
          setWindowLocation(locationSearch);
          mountComponent();
          await waitForPromises();
        });

        it('renders the issues', () => {
          expect(findIssuableList().props('issuables')).toEqual(
            defaultQueryResponse.data.issues.nodes,
          );
        });

        it('does not render empty state', () => {
          expect(findEmptyState().exists()).toBe(false);
        });
      });

      describe('when there are no issues returned', () => {
        beforeEach(async () => {
          setWindowLocation(locationSearch);
          mountComponent({
            issuesQueryHandler: jest.fn().mockResolvedValue(emptyIssuesQueryResponse),
          });
          await waitForPromises();
        });

        it('renders no issues', () => {
          expect(findIssuableList().props('issuables')).toEqual([]);
        });

        it('renders empty state', () => {
          expect(findEmptyState().props()).toMatchObject({
            description: i18n.noSearchResultsDescription,
            svgPath: defaultProvide.emptyStateWithFilterSvgPath,
            title: i18n.noSearchResultsTitle,
          });
        });
      });
    });

    describe('with no search query', () => {
      let issuesQueryHandler;

      beforeEach(async () => {
        issuesQueryHandler = jest.fn().mockResolvedValue(defaultQueryResponse);
        mountComponent({ issuesQueryHandler });
        await waitForPromises();
      });

      it('does not call issues query', () => {
        expect(issuesQueryHandler).not.toHaveBeenCalled();
      });

      it('renders empty state', () => {
        expect(findEmptyState().props()).toMatchObject({
          description: null,
          svgPath: defaultProvide.emptyStateWithoutFilterSvgPath,
          title: i18n.noSearchNoFilterTitle,
        });
      });
    });
  });

  describe('initial url params', () => {
    describe('search', () => {
      it('is set from the url params', () => {
        setWindowLocation(locationSearch);
        mountComponent();

        expect(findIssuableList().props('urlParams')).toMatchObject({ search: 'find issues' });
      });
    });

    describe('sort', () => {
      describe('when initial sort value uses old enum values', () => {
        const oldEnumSortValues = Object.values(urlSortParams);

        it.each(oldEnumSortValues)('initial sort is set with value %s', (sort) => {
          mountComponent({ provide: { initialSort: sort } });

          expect(findIssuableList().props('initialSortBy')).toBe(getSortKey(sort));
        });
      });

      describe('when initial sort value uses new GraphQL enum values', () => {
        const graphQLEnumSortValues = Object.keys(urlSortParams);

        it.each(graphQLEnumSortValues)('initial sort is set with value %s', (sort) => {
          mountComponent({ provide: { initialSort: sort.toLowerCase() } });

          expect(findIssuableList().props('initialSortBy')).toBe(sort);
        });
      });

      describe('when initial sort value is invalid', () => {
        it.each(['', 'asdf', null, undefined])(
          'initial sort is set to value CREATED_DESC',
          (sort) => {
            mountComponent({ provide: { initialSort: sort } });

            expect(findIssuableList().props('initialSortBy')).toBe(CREATED_DESC);
          },
        );
      });
    });

    describe('state', () => {
      it('is set from the url params', () => {
        const initialState = STATUS_ALL;
        setWindowLocation(`?state=${initialState}`);
        mountComponent();

        expect(findIssuableList().props('currentTab')).toBe(initialState);
      });
    });

    describe('filter tokens', () => {
      it('is set from the url params', () => {
        setWindowLocation(locationSearch);
        mountComponent();

        expect(findIssuableList().props('initialFilterValue')).toEqual(filteredTokens);
      });
    });
  });

  describe('errors', () => {
    describe.each`
      error                      | mountOption                   | message
      ${'fetching issues'}       | ${'issuesQueryHandler'}       | ${i18n.errorFetchingIssues}
      ${'fetching issue counts'} | ${'issuesCountsQueryHandler'} | ${i18n.errorFetchingCounts}
    `('when there is an error $error', ({ mountOption, message }) => {
      beforeEach(async () => {
        setWindowLocation(locationSearch);
        mountComponent({ [mountOption]: jest.fn().mockRejectedValue(new Error('ERROR')) });
        await waitForPromises();
      });

      it('shows an error message', () => {
        expect(findIssuableList().props('error')).toBe(message);
        expect(Sentry.captureException).toHaveBeenCalledWith(new Error('ERROR'));
      });
    });

    it('clears error message when "dismiss-alert" event is emitted from IssuableList', async () => {
      mountComponent({ issuesQueryHandler: jest.fn().mockRejectedValue(new Error()) });

      findIssuableList().vm.$emit('dismiss-alert');
      await nextTick();

      expect(findIssuableList().props('error')).toBeNull();
    });
  });

  describe('tokens', () => {
    const mockCurrentUser = {
      id: 1,
      name: 'Administrator',
      username: 'root',
      avatar_url: 'avatar/url',
    };

    beforeEach(() => {
      window.gon = {
        current_user_id: mockCurrentUser.id,
        current_user_fullname: mockCurrentUser.name,
        current_username: mockCurrentUser.username,
        current_user_avatar_url: mockCurrentUser.avatar_url,
      };
      mountComponent();
    });

    it('renders all tokens alphabetically', () => {
      const preloadedUsers = [{ ...mockCurrentUser, id: mockCurrentUser.id }];

      expect(findIssuableList().props('searchTokens')).toMatchObject([
        { type: TOKEN_TYPE_ASSIGNEE, preloadedUsers },
        { type: TOKEN_TYPE_AUTHOR, preloadedUsers },
        { type: TOKEN_TYPE_CONFIDENTIAL },
        { type: TOKEN_TYPE_LABEL },
        { type: TOKEN_TYPE_MILESTONE },
        { type: TOKEN_TYPE_MY_REACTION },
        { type: TOKEN_TYPE_SEARCH_WITHIN },
        { type: TOKEN_TYPE_TYPE },
      ]);
    });
  });

  describe('events', () => {
    describe('when "click-tab" event is emitted by IssuableList', () => {
      beforeEach(() => {
        mountComponent();

        findIssuableList().vm.$emit('click-tab', STATUS_CLOSED);
      });

      it('updates ui to the new tab', () => {
        expect(findIssuableList().props('currentTab')).toBe(STATUS_CLOSED);
      });

      it('updates url to the new tab', () => {
        expect(findIssuableList().props('urlParams')).toMatchObject({
          state: STATUS_CLOSED,
        });
      });
    });

    describe.each(['next-page', 'previous-page'])(
      'when "%s" event is emitted by IssuableList',
      (event) => {
        beforeEach(() => {
          mountComponent();

          findIssuableList().vm.$emit(event);
        });

        it('scrolls to the top', () => {
          expect(scrollUp).toHaveBeenCalled();
        });
      },
    );

    describe('when "sort" event is emitted by IssuableList', () => {
      it.each(Object.keys(urlSortParams))(
        'updates to the new sort when payload is `%s`',
        async (sortKey) => {
          // Ensure initial sort key is different so we can trigger an update when emitting a sort key
          if (sortKey === CREATED_DESC) {
            mountComponent({ provide: { initialSort: UPDATED_DESC } });
          } else {
            mountComponent();
          }

          findIssuableList().vm.$emit('sort', sortKey);
          await nextTick();

          expect(findIssuableList().props('urlParams')).toMatchObject({
            sort: urlSortParams[sortKey],
          });
        },
      );

      describe('when user is signed in', () => {
        it('calls mutation to save sort preference', () => {
          const mutationMock = jest.fn().mockResolvedValue(setSortPreferenceMutationResponse);
          mountComponent({ sortPreferenceMutationHandler: mutationMock });

          findIssuableList().vm.$emit('sort', UPDATED_DESC);

          expect(mutationMock).toHaveBeenCalledWith({ input: { issuesSort: UPDATED_DESC } });
        });

        it('captures error when mutation response has errors', async () => {
          const mutationMock = jest
            .fn()
            .mockResolvedValue(setSortPreferenceMutationResponseWithErrors);
          mountComponent({ sortPreferenceMutationHandler: mutationMock });

          findIssuableList().vm.$emit('sort', UPDATED_DESC);
          await waitForPromises();

          expect(Sentry.captureException).toHaveBeenCalledWith(new Error('oh no!'));
        });
      });

      describe('when user is signed out', () => {
        it('does not call mutation to save sort preference', () => {
          const mutationMock = jest.fn().mockResolvedValue(setSortPreferenceMutationResponse);
          mountComponent({
            provide: { isSignedIn: false },
            sortPreferenceMutationHandler: mutationMock,
          });

          findIssuableList().vm.$emit('sort', CREATED_DESC);

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