summaryrefslogtreecommitdiff
path: root/spec/frontend/pipelines/pipelines_spec.js
blob: d2b30c937464e1229f6ef6653cb7d4786d341cc7 (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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
import '~/commons';
import { GlButton, GlEmptyState, GlFilteredSearch, GlLoadingIcon, GlPagination } from '@gitlab/ui';
import { mount } from '@vue/test-utils';
import MockAdapter from 'axios-mock-adapter';
import { chunk } from 'lodash';
import { nextTick } from 'vue';
import mockPipelinesResponse from 'test_fixtures/pipelines/pipelines.json';
import setWindowLocation from 'helpers/set_window_location_helper';
import { TEST_HOST } from 'helpers/test_constants';
import { extendedWrapper } from 'helpers/vue_test_utils_helper';
import waitForPromises from 'helpers/wait_for_promises';
import Api from '~/api';
import createFlash from '~/flash';
import axios from '~/lib/utils/axios_utils';
import NavigationControls from '~/pipelines/components/pipelines_list/nav_controls.vue';
import PipelinesComponent from '~/pipelines/components/pipelines_list/pipelines.vue';
import PipelinesCiTemplates from '~/pipelines/components/pipelines_list/empty_state/pipelines_ci_templates.vue';
import PipelinesTableComponent from '~/pipelines/components/pipelines_list/pipelines_table.vue';
import { RAW_TEXT_WARNING } from '~/pipelines/constants';
import Store from '~/pipelines/stores/pipelines_store';
import NavigationTabs from '~/vue_shared/components/navigation_tabs.vue';
import TablePagination from '~/vue_shared/components/pagination/table_pagination.vue';

import { stageReply, users, mockSearch, branches } from './mock_data';

jest.mock('~/flash');

const mockProjectPath = 'twitter/flight';
const mockProjectId = '21';
const mockDefaultBranchName = 'main';
const mockPipelinesEndpoint = `/${mockProjectPath}/pipelines.json`;
const mockPipelinesIds = mockPipelinesResponse.pipelines.map(({ id }) => id);
const mockPipelineWithStages = mockPipelinesResponse.pipelines.find(
  (p) => p.details.stages && p.details.stages.length,
);

describe('Pipelines', () => {
  let wrapper;
  let mock;

  const paths = {
    emptyStateSvgPath: '/assets/illustrations/pipelines_empty.svg',
    errorStateSvgPath: '/assets/illustrations/pipelines_failed.svg',
    noPipelinesSvgPath: '/assets/illustrations/pipelines_pending.svg',
    ciLintPath: '/ci/lint',
    resetCachePath: `${mockProjectPath}/settings/ci_cd/reset_cache`,
    newPipelinePath: `${mockProjectPath}/pipelines/new`,
    ciRunnerSettingsPath: `${mockProjectPath}/-/settings/ci_cd#js-runners-settings`,
  };

  const noPermissions = {
    emptyStateSvgPath: '/assets/illustrations/pipelines_empty.svg',
    errorStateSvgPath: '/assets/illustrations/pipelines_failed.svg',
    noPipelinesSvgPath: '/assets/illustrations/pipelines_pending.svg',
  };

  const defaultProps = {
    hasGitlabCi: true,
    canCreatePipeline: true,
    ...paths,
  };

  const findFilteredSearch = () => wrapper.findComponent(GlFilteredSearch);
  const findEmptyState = () => wrapper.findComponent(GlEmptyState);
  const findNavigationTabs = () => wrapper.findComponent(NavigationTabs);
  const findNavigationControls = () => wrapper.findComponent(NavigationControls);
  const findPipelinesTable = () => wrapper.findComponent(PipelinesTableComponent);
  const findTablePagination = () => wrapper.findComponent(TablePagination);

  const findTab = (tab) => wrapper.findByTestId(`pipelines-tab-${tab}`);
  const findPipelineKeyDropdown = () => wrapper.findByTestId('pipeline-key-dropdown');
  const findRunPipelineButton = () => wrapper.findByTestId('run-pipeline-button');
  const findCiLintButton = () => wrapper.findByTestId('ci-lint-button');
  const findCleanCacheButton = () => wrapper.findByTestId('clear-cache-button');
  const findStagesDropdownToggle = () =>
    wrapper.find('[data-testid="mini-pipeline-graph-dropdown"] .dropdown-toggle');
  const findPipelineUrlLinks = () => wrapper.findAll('[data-testid="pipeline-url-link"]');

  const createComponent = (props = defaultProps) => {
    wrapper = extendedWrapper(
      mount(PipelinesComponent, {
        provide: {
          pipelineEditorPath: '',
          suggestedCiTemplates: [],
        },
        propsData: {
          store: new Store(),
          projectId: mockProjectId,
          defaultBranchName: mockDefaultBranchName,
          endpoint: mockPipelinesEndpoint,
          params: {},
          ...props,
        },
      }),
    );
  };

  beforeEach(() => {
    setWindowLocation(TEST_HOST);
  });

  beforeEach(() => {
    mock = new MockAdapter(axios);

    jest.spyOn(window.history, 'pushState');
    jest.spyOn(Api, 'projectUsers').mockResolvedValue(users);
    jest.spyOn(Api, 'branches').mockResolvedValue({ data: branches });
  });

  afterEach(() => {
    wrapper.destroy();
    mock.reset();
    window.history.pushState.mockReset();
  });

  describe('when pipelines are not yet loaded', () => {
    beforeEach(async () => {
      createComponent();
      await nextTick();
    });

    it('shows loading state when the app is loading', () => {
      expect(wrapper.find(GlLoadingIcon).exists()).toBe(true);
    });

    it('does not display tabs when the first request has not yet been made', () => {
      expect(findNavigationTabs().exists()).toBe(false);
    });

    it('does not display buttons', () => {
      expect(findNavigationControls().exists()).toBe(false);
    });
  });

  describe('when there are pipelines in the project', () => {
    beforeEach(() => {
      mock
        .onGet(mockPipelinesEndpoint, { params: { scope: 'all', page: '1' } })
        .reply(200, mockPipelinesResponse);
    });

    describe('when user has no permissions', () => {
      beforeEach(async () => {
        createComponent({ hasGitlabCi: true, canCreatePipeline: false, ...noPermissions });
        await waitForPromises();
      });

      it('renders "All" tab with count different from "0"', () => {
        expect(findTab('all').text()).toMatchInterpolatedText('All 3');
      });

      it('does not render buttons', () => {
        expect(findNavigationControls().exists()).toBe(false);

        expect(findRunPipelineButton().exists()).toBe(false);
        expect(findCiLintButton().exists()).toBe(false);
        expect(findCleanCacheButton().exists()).toBe(false);
      });

      it('renders pipelines in a table', () => {
        expect(findPipelinesTable().exists()).toBe(true);

        expect(findPipelineUrlLinks()).toHaveLength(mockPipelinesIds.length);
        expect(findPipelineUrlLinks().at(0).text()).toBe(`#${mockPipelinesIds[0]}`);
        expect(findPipelineUrlLinks().at(1).text()).toBe(`#${mockPipelinesIds[1]}`);
        expect(findPipelineUrlLinks().at(2).text()).toBe(`#${mockPipelinesIds[2]}`);
      });
    });

    describe('when user has permissions', () => {
      beforeEach(async () => {
        createComponent();
        await waitForPromises();
      });

      it('should set up navigation tabs', () => {
        expect(findNavigationTabs().props('tabs')).toEqual([
          { name: 'All', scope: 'all', count: '3', isActive: true },
          { name: 'Finished', scope: 'finished', count: undefined, isActive: false },
          { name: 'Branches', scope: 'branches', isActive: false },
          { name: 'Tags', scope: 'tags', isActive: false },
        ]);
      });

      it('renders "All" tab with count different from "0"', () => {
        expect(findTab('all').text()).toMatchInterpolatedText('All 3');
      });

      it('should render other navigation tabs', () => {
        expect(findTab('finished').text()).toBe('Finished');
        expect(findTab('branches').text()).toBe('Branches');
        expect(findTab('tags').text()).toBe('Tags');
      });

      it('shows navigation controls', () => {
        expect(findNavigationControls().exists()).toBe(true);
      });

      it('renders Run pipeline link', () => {
        expect(findRunPipelineButton().attributes('href')).toBe(paths.newPipelinePath);
      });

      it('renders CI lint link', () => {
        expect(findCiLintButton().attributes('href')).toBe(paths.ciLintPath);
      });

      it('renders Clear runner cache button', () => {
        expect(findCleanCacheButton().text()).toBe('Clear runner caches');
      });

      it('renders pipelines in a table', () => {
        expect(findPipelinesTable().exists()).toBe(true);

        expect(findPipelineUrlLinks()).toHaveLength(mockPipelinesIds.length);
        expect(findPipelineUrlLinks().at(0).text()).toBe(`#${mockPipelinesIds[0]}`);
        expect(findPipelineUrlLinks().at(1).text()).toBe(`#${mockPipelinesIds[1]}`);
        expect(findPipelineUrlLinks().at(2).text()).toBe(`#${mockPipelinesIds[2]}`);
      });

      describe('when user goes to a tab', () => {
        const goToTab = (tab) => {
          findNavigationTabs().vm.$emit('onChangeTab', tab);
        };

        describe('when the scope in the tab has pipelines', () => {
          const mockFinishedPipeline = mockPipelinesResponse.pipelines[0];

          beforeEach(async () => {
            mock
              .onGet(mockPipelinesEndpoint, { params: { scope: 'finished', page: '1' } })
              .reply(200, {
                pipelines: [mockFinishedPipeline],
                count: mockPipelinesResponse.count,
              });

            goToTab('finished');

            await waitForPromises();
          });

          it('should filter pipelines', async () => {
            expect(findPipelinesTable().exists()).toBe(true);

            expect(findPipelineUrlLinks()).toHaveLength(1);
            expect(findPipelineUrlLinks().at(0).text()).toBe(`#${mockFinishedPipeline.id}`);
          });

          it('should update browser bar', () => {
            expect(window.history.pushState).toHaveBeenCalledTimes(1);
            expect(window.history.pushState).toHaveBeenCalledWith(
              expect.anything(),
              expect.anything(),
              `${window.location.pathname}?scope=finished&page=1`,
            );
          });
        });

        describe('when the scope in the tab is empty', () => {
          beforeEach(async () => {
            mock
              .onGet(mockPipelinesEndpoint, { params: { scope: 'branches', page: '1' } })
              .reply(200, {
                pipelines: [],
                count: mockPipelinesResponse.count,
              });

            goToTab('branches');

            await waitForPromises();
          });

          it('should filter pipelines', async () => {
            expect(findEmptyState().text()).toBe('There are currently no pipelines.');
          });

          it('should update browser bar', () => {
            expect(window.history.pushState).toHaveBeenCalledTimes(1);
            expect(window.history.pushState).toHaveBeenCalledWith(
              expect.anything(),
              expect.anything(),
              `${window.location.pathname}?scope=branches&page=1`,
            );
          });
        });
      });

      describe('when user triggers a filtered search', () => {
        const mockFilteredPipeline = mockPipelinesResponse.pipelines[1];

        let expectedParams;

        beforeEach(async () => {
          expectedParams = {
            page: '1',
            scope: 'all',
            username: 'root',
            ref: 'main',
            status: 'pending',
          };

          mock
            .onGet(mockPipelinesEndpoint, {
              params: expectedParams,
            })
            .replyOnce(200, {
              pipelines: [mockFilteredPipeline],
              count: mockPipelinesResponse.count,
            });

          findFilteredSearch().vm.$emit('submit', mockSearch);

          await waitForPromises();
        });

        it('requests data with query params on filter submit', async () => {
          expect(mock.history.get[1].params).toEqual(expectedParams);
        });

        it('renders filtered pipelines', async () => {
          expect(findPipelineUrlLinks()).toHaveLength(1);
          expect(findPipelineUrlLinks().at(0).text()).toBe(`#${mockFilteredPipeline.id}`);
        });

        it('should update browser bar', () => {
          expect(window.history.pushState).toHaveBeenCalledTimes(1);
          expect(window.history.pushState).toHaveBeenCalledWith(
            expect.anything(),
            expect.anything(),
            `${window.location.pathname}?page=1&scope=all&username=root&ref=main&status=pending`,
          );
        });
      });

      describe('when user triggers a filtered search with raw text', () => {
        beforeEach(async () => {
          findFilteredSearch().vm.$emit('submit', ['rawText']);

          await waitForPromises();
        });

        it('requests data with query params on filter submit', async () => {
          expect(mock.history.get[1].params).toEqual({ page: '1', scope: 'all' });
        });

        it('displays a warning message if raw text search is used', () => {
          expect(createFlash).toHaveBeenCalledTimes(1);
          expect(createFlash).toHaveBeenCalledWith({ message: RAW_TEXT_WARNING, type: 'warning' });
        });

        it('should update browser bar', () => {
          expect(window.history.pushState).toHaveBeenCalledTimes(1);
          expect(window.history.pushState).toHaveBeenCalledWith(
            expect.anything(),
            expect.anything(),
            `${window.location.pathname}?page=1&scope=all`,
          );
        });
      });
    });
  });

  describe('when there are multiple pages of pipelines', () => {
    const mockPageSize = 2;
    const mockPageHeaders = ({ page = 1 } = {}) => {
      return {
        'X-PER-PAGE': `${mockPageSize}`,
        'X-PREV-PAGE': `${page - 1}`,
        'X-PAGE': `${page}`,
        'X-NEXT-PAGE': `${page + 1}`,
      };
    };
    const [firstPage, secondPage] = chunk(mockPipelinesResponse.pipelines, mockPageSize);

    const goToPage = (page) => {
      findTablePagination().find(GlPagination).vm.$emit('input', page);
    };

    beforeEach(async () => {
      mock.onGet(mockPipelinesEndpoint, { params: { scope: 'all', page: '1' } }).reply(
        200,
        {
          pipelines: firstPage,
          count: mockPipelinesResponse.count,
        },
        mockPageHeaders({ page: 1 }),
      );
      mock.onGet(mockPipelinesEndpoint, { params: { scope: 'all', page: '2' } }).reply(
        200,
        {
          pipelines: secondPage,
          count: mockPipelinesResponse.count,
        },
        mockPageHeaders({ page: 2 }),
      );

      createComponent();

      await waitForPromises();
    });

    it('shows the first page of pipelines', () => {
      expect(findPipelineUrlLinks()).toHaveLength(firstPage.length);
      expect(findPipelineUrlLinks().at(0).text()).toBe(`#${firstPage[0].id}`);
      expect(findPipelineUrlLinks().at(1).text()).toBe(`#${firstPage[1].id}`);
    });

    it('should not update browser bar', () => {
      expect(window.history.pushState).not.toHaveBeenCalled();
    });

    describe('when user goes to next page', () => {
      beforeEach(async () => {
        goToPage(2);
        await waitForPromises();
      });

      it('should update page and keep scope the same scope', () => {
        expect(findPipelineUrlLinks()).toHaveLength(secondPage.length);
        expect(findPipelineUrlLinks().at(0).text()).toBe(`#${secondPage[0].id}`);
      });

      it('should update browser bar', () => {
        expect(window.history.pushState).toHaveBeenCalledTimes(1);
        expect(window.history.pushState).toHaveBeenCalledWith(
          expect.anything(),
          expect.anything(),
          `${window.location.pathname}?page=2&scope=all`,
        );
      });
    });
  });

  describe('when pipelines can be polled', () => {
    beforeEach(() => {
      const emptyResponse = {
        pipelines: [],
        count: { all: '0' },
      };

      // Mock no pipelines in the first attempt
      mock
        .onGet(mockPipelinesEndpoint, { params: { scope: 'all', page: '1' } })
        .replyOnce(200, emptyResponse, {
          'POLL-INTERVAL': 100,
        });
      // Mock pipelines in the next attempt
      mock
        .onGet(mockPipelinesEndpoint, { params: { scope: 'all', page: '1' } })
        .reply(200, mockPipelinesResponse, {
          'POLL-INTERVAL': 100,
        });
    });

    describe('data is loaded for the first time', () => {
      beforeEach(async () => {
        createComponent();
        await waitForPromises();
      });

      it('shows tabs', () => {
        expect(findNavigationTabs().exists()).toBe(true);
      });

      it('should update page and keep scope the same scope', () => {
        expect(findPipelineUrlLinks()).toHaveLength(0);
      });

      describe('data is loaded for a second time', () => {
        beforeEach(async () => {
          jest.runOnlyPendingTimers();
          await waitForPromises();
        });

        it('shows tabs', () => {
          expect(findNavigationTabs().exists()).toBe(true);
        });

        it('is loading after a time', async () => {
          expect(findPipelineUrlLinks()).toHaveLength(mockPipelinesIds.length);
          expect(findPipelineUrlLinks().at(0).text()).toBe(`#${mockPipelinesIds[0]}`);
          expect(findPipelineUrlLinks().at(1).text()).toBe(`#${mockPipelinesIds[1]}`);
          expect(findPipelineUrlLinks().at(2).text()).toBe(`#${mockPipelinesIds[2]}`);
        });
      });
    });
  });

  describe('when no pipelines exist', () => {
    beforeEach(() => {
      mock.onGet(mockPipelinesEndpoint, { params: { scope: 'all', page: '1' } }).reply(200, {
        pipelines: [],
        count: { all: '0' },
      });
    });

    describe('when CI is enabled and user has permissions', () => {
      beforeEach(async () => {
        createComponent();
        await waitForPromises();
      });

      it('renders tab with count of "0"', () => {
        expect(findNavigationTabs().exists()).toBe(true);
        expect(findTab('all').text()).toMatchInterpolatedText('All 0');
      });

      it('renders Run pipeline link', () => {
        expect(findRunPipelineButton().attributes('href')).toBe(paths.newPipelinePath);
      });

      it('renders CI lint link', () => {
        expect(findCiLintButton().attributes('href')).toBe(paths.ciLintPath);
      });

      it('renders Clear runner cache button', () => {
        expect(findCleanCacheButton().text()).toBe('Clear runner caches');
      });

      it('renders empty state', () => {
        expect(findEmptyState().text()).toBe('There are currently no pipelines.');
      });

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

      it('renders the pipeline key dropdown', () => {
        expect(findPipelineKeyDropdown().exists()).toBe(true);
      });

      it('renders tab empty state finished scope', async () => {
        mock.onGet(mockPipelinesEndpoint, { params: { scope: 'finished', page: '1' } }).reply(200, {
          pipelines: [],
          count: { all: '0' },
        });

        findNavigationTabs().vm.$emit('onChangeTab', 'finished');

        await waitForPromises();

        expect(findEmptyState().text()).toBe('There are currently no finished pipelines.');
      });
    });

    describe('when CI is not enabled and user has permissions', () => {
      beforeEach(async () => {
        createComponent({ hasGitlabCi: false, canCreatePipeline: true, ...paths });
        await waitForPromises();
      });

      it('renders the CI/CD templates', () => {
        expect(wrapper.findComponent(PipelinesCiTemplates).exists()).toBe(true);
      });

      it('does not render filtered search', () => {
        expect(findFilteredSearch().exists()).toBe(false);
      });

      it('does not render the pipeline key dropdown', () => {
        expect(findPipelineKeyDropdown().exists()).toBe(false);
      });

      it('does not render tabs nor buttons', () => {
        expect(findNavigationTabs().exists()).toBe(false);
        expect(findTab('all').exists()).toBe(false);
        expect(findRunPipelineButton().exists()).toBe(false);
        expect(findCiLintButton().exists()).toBe(false);
        expect(findCleanCacheButton().exists()).toBe(false);
      });
    });

    describe('when CI is not enabled and user has no permissions', () => {
      beforeEach(async () => {
        createComponent({ hasGitlabCi: false, canCreatePipeline: false, ...noPermissions });
        await waitForPromises();
      });

      it('renders empty state without button to set CI', () => {
        expect(findEmptyState().text()).toBe(
          'This project is not currently set up to run pipelines.',
        );

        expect(findEmptyState().find(GlButton).exists()).toBe(false);
      });

      it('does not render tabs or buttons', () => {
        expect(findTab('all').exists()).toBe(false);
        expect(findRunPipelineButton().exists()).toBe(false);
        expect(findCiLintButton().exists()).toBe(false);
        expect(findCleanCacheButton().exists()).toBe(false);
      });
    });

    describe('when CI is enabled and user has no permissions', () => {
      beforeEach(() => {
        createComponent({ hasGitlabCi: true, canCreatePipeline: false, ...noPermissions });

        return waitForPromises();
      });

      it('renders tab with count of "0"', () => {
        expect(findTab('all').text()).toMatchInterpolatedText('All 0');
      });

      it('does not render buttons', () => {
        expect(findRunPipelineButton().exists()).toBe(false);
        expect(findCiLintButton().exists()).toBe(false);
        expect(findCleanCacheButton().exists()).toBe(false);
      });

      it('renders empty state', () => {
        expect(findEmptyState().text()).toBe('There are currently no pipelines.');
      });
    });
  });

  describe('when a pipeline with stages exists', () => {
    describe('updates results when a staged is clicked', () => {
      let stopMock;
      let restartMock;
      let cancelMock;

      beforeEach(() => {
        mock.onGet(mockPipelinesEndpoint, { scope: 'all', page: '1' }).reply(
          200,
          {
            pipelines: [mockPipelineWithStages],
            count: { all: '1' },
          },
          {
            'POLL-INTERVAL': 100,
          },
        );

        mock.onGet(mockPipelineWithStages.details.stages[0].dropdown_path).reply(200, stageReply);

        createComponent();

        stopMock = jest.spyOn(wrapper.vm.poll, 'stop');
        restartMock = jest.spyOn(wrapper.vm.poll, 'restart');
        cancelMock = jest.spyOn(wrapper.vm.service.cancelationSource, 'cancel');
      });

      describe('when a request is being made', () => {
        beforeEach(async () => {
          mock.onGet(mockPipelinesEndpoint).reply(200, mockPipelinesResponse);

          await waitForPromises();
        });

        it('stops polling, cancels the request, & restarts polling', async () => {
          // Mock init a polling cycle
          wrapper.vm.poll.options.notificationCallback(true);

          findStagesDropdownToggle().trigger('click');

          await waitForPromises();

          expect(cancelMock).toHaveBeenCalled();
          expect(stopMock).toHaveBeenCalled();
          expect(restartMock).toHaveBeenCalled();
        });

        it('stops polling & restarts polling', async () => {
          findStagesDropdownToggle().trigger('click');

          await waitForPromises();

          expect(cancelMock).not.toHaveBeenCalled();
          expect(stopMock).toHaveBeenCalled();
          expect(restartMock).toHaveBeenCalled();
        });
      });
    });
  });

  describe('when pipelines cannot be loaded', () => {
    beforeEach(async () => {
      mock.onGet(mockPipelinesEndpoint).reply(500, {});
    });

    describe('when user has no permissions', () => {
      beforeEach(async () => {
        createComponent({ hasGitlabCi: false, canCreatePipeline: true, ...noPermissions });

        await waitForPromises();
      });

      it('renders tabs', () => {
        expect(findNavigationTabs().exists()).toBe(true);
        expect(findTab('all').text()).toBe('All');
      });

      it('does not render buttons', () => {
        expect(findRunPipelineButton().exists()).toBe(false);
        expect(findCiLintButton().exists()).toBe(false);
        expect(findCleanCacheButton().exists()).toBe(false);
      });

      it('shows error state', () => {
        expect(findEmptyState().text()).toBe(
          'There was an error fetching the pipelines. Try again in a few moments or contact your support team.',
        );
      });
    });

    describe('when user has permissions', () => {
      beforeEach(async () => {
        createComponent();

        await waitForPromises();
      });

      it('renders tabs', () => {
        expect(findTab('all').text()).toBe('All');
      });

      it('renders buttons', () => {
        expect(findRunPipelineButton().attributes('href')).toBe(paths.newPipelinePath);

        expect(findCiLintButton().attributes('href')).toBe(paths.ciLintPath);
        expect(findCleanCacheButton().text()).toBe('Clear runner caches');
      });

      it('shows error state', () => {
        expect(findEmptyState().text()).toBe(
          'There was an error fetching the pipelines. Try again in a few moments or contact your support team.',
        );
      });
    });
  });
});