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

package_files_spec.js « details « components « package_registry « packages_and_registries « frontend « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 2b60684e60a1240a3d7d816041445e00529ccb05 (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
import { GlAlert, GlDropdown, GlButton, GlFormCheckbox, GlLoadingIcon, GlModal } from '@gitlab/ui';
import Vue, { nextTick } from 'vue';
import VueApollo from 'vue-apollo';
import { stubComponent } from 'helpers/stub_component';
import { mountExtended, extendedWrapper } from 'helpers/vue_test_utils_helper';
import createMockApollo from 'helpers/mock_apollo_helper';
import waitForPromises from 'helpers/wait_for_promises';
import Tracking from '~/tracking';
import { s__ } from '~/locale';
import { createAlert } from '~/alert';
import {
  packageFiles as packageFilesMock,
  packageFilesQuery,
  packageDestroyFilesMutation,
  packageDestroyFilesMutationError,
} from 'jest/packages_and_registries/package_registry/mock_data';
import {
  DOWNLOAD_PACKAGE_ASSET_TRACKING_ACTION,
  DELETE_ALL_PACKAGE_FILES_MODAL_CONTENT,
  DELETE_LAST_PACKAGE_FILE_MODAL_CONTENT,
  DELETE_PACKAGE_FILE_SUCCESS_MESSAGE,
  DELETE_PACKAGE_FILE_ERROR_MESSAGE,
  DELETE_PACKAGE_FILES_SUCCESS_MESSAGE,
  DELETE_PACKAGE_FILES_ERROR_MESSAGE,
} from '~/packages_and_registries/package_registry/constants';
import PackageFiles from '~/packages_and_registries/package_registry/components/details/package_files.vue';
import FileIcon from '~/vue_shared/components/file_icon.vue';
import TimeAgoTooltip from '~/vue_shared/components/time_ago_tooltip.vue';

import getPackageFiles from '~/packages_and_registries/package_registry/graphql/queries/get_package_files.query.graphql';
import destroyPackageFilesMutation from '~/packages_and_registries/package_registry/graphql/mutations/destroy_package_files.mutation.graphql';

Vue.use(VueApollo);
jest.mock('~/alert');

describe('Package Files', () => {
  let wrapper;
  let apolloProvider;

  const findAllRows = () => wrapper.findAllByTestId('file-row');
  const findDeleteSelectedButton = () => wrapper.findByTestId('delete-selected');
  const findDeleteFilesModal = () => wrapper.findByTestId('delete-files-modal');
  const findFirstRow = () => extendedWrapper(findAllRows().at(0));
  const findSecondRow = () => extendedWrapper(findAllRows().at(1));
  const findPackageFilesAlert = () => wrapper.findComponent(GlAlert);
  const findLoadingIcon = () => wrapper.findComponent(GlLoadingIcon);
  const findFirstRowDownloadLink = () => findFirstRow().findByTestId('download-link');
  const findFirstRowFileIcon = () => findFirstRow().findComponent(FileIcon);
  const findFirstRowCreatedAt = () => findFirstRow().findComponent(TimeAgoTooltip);
  const findFirstActionMenu = () => extendedWrapper(findFirstRow().findComponent(GlDropdown));
  const findActionMenuDelete = () => findFirstActionMenu().findByTestId('delete-file');
  const findFirstToggleDetailsButton = () => findFirstRow().findComponent(GlButton);
  const findFirstRowShaComponent = (id) => wrapper.findByTestId(id);
  const findCheckAllCheckbox = () => wrapper.findByTestId('package-files-checkbox-all');
  const findAllRowCheckboxes = () => wrapper.findAllByTestId('package-files-checkbox');

  const files = packageFilesMock();
  const [file] = files;

  const showMock = jest.fn();
  const eventCategory = 'UI::NpmPackages';

  const createComponent = ({
    packageId = '1',
    packageType = 'NPM',
    projectPath = 'gitlab-test',
    canDelete = true,
    stubs,
    resolver = jest.fn().mockResolvedValue(packageFilesQuery({ files: [file] })),
    filesDeleteMutationResolver = jest.fn().mockResolvedValue(packageDestroyFilesMutation()),
  } = {}) => {
    const requestHandlers = [
      [getPackageFiles, resolver],
      [destroyPackageFilesMutation, filesDeleteMutationResolver],
    ];
    apolloProvider = createMockApollo(requestHandlers);

    wrapper = mountExtended(PackageFiles, {
      apolloProvider,
      propsData: {
        canDelete,
        packageId,
        packageType,
        projectPath,
      },
      stubs: {
        GlTable: false,
        GlModal: stubComponent(GlModal, {
          methods: {
            show: showMock,
          },
        }),
        ...stubs,
      },
    });
  };

  describe('rows', () => {
    it('do not get rendered when query is loading', () => {
      createComponent();

      expect(findLoadingIcon().exists()).toBe(true);
      expect(findDeleteSelectedButton().props('disabled')).toBe(true);
    });

    it('renders a single file for an npm package', async () => {
      createComponent();
      await waitForPromises();

      expect(findAllRows()).toHaveLength(1);
      expect(findLoadingIcon().exists()).toBe(false);
    });

    it('renders multiple files for a package that contains more than one file', async () => {
      createComponent({ resolver: jest.fn().mockResolvedValue(packageFilesQuery()) });
      await waitForPromises();

      expect(findAllRows()).toHaveLength(2);
    });

    it('does not render gl-alert', async () => {
      createComponent();
      await waitForPromises();

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

    it('renders gl-alert if load fails', async () => {
      createComponent({ resolver: jest.fn().mockRejectedValue() });
      await waitForPromises();

      expect(findPackageFilesAlert().exists()).toBe(true);
      expect(findPackageFilesAlert().text()).toBe(
        s__('PackageRegistry|Something went wrong while fetching package assets.'),
      );
    });
  });

  describe('link', () => {
    beforeEach(async () => {
      createComponent();
      await waitForPromises();
    });

    it('exists', () => {
      expect(findFirstRowDownloadLink().exists()).toBe(true);
    });

    it('has the correct attrs bound', () => {
      expect(findFirstRowDownloadLink().attributes('href')).toBe(file.downloadPath);
    });

    it('tracks "download-file" event on click', () => {
      const eventSpy = jest.spyOn(Tracking, 'event');

      findFirstRowDownloadLink().vm.$emit('click');

      expect(eventSpy).toHaveBeenCalledWith(
        eventCategory,
        DOWNLOAD_PACKAGE_ASSET_TRACKING_ACTION,
        expect.any(Object),
      );
    });
  });

  describe('file-icon', () => {
    beforeEach(async () => {
      createComponent();
      await waitForPromises();
    });

    it('exists', () => {
      expect(findFirstRowFileIcon().exists()).toBe(true);
    });

    it('has the correct props bound', () => {
      expect(findFirstRowFileIcon().props('fileName')).toBe(file.fileName);
    });
  });

  describe('time-ago tooltip', () => {
    beforeEach(async () => {
      createComponent();
      await waitForPromises();
    });

    it('exists', () => {
      expect(findFirstRowCreatedAt().exists()).toBe(true);
    });

    it('has the correct props bound', () => {
      expect(findFirstRowCreatedAt().props('time')).toBe(file.createdAt);
    });
  });

  describe('action menu', () => {
    describe('when the user can delete', () => {
      beforeEach(async () => {
        createComponent();
        await waitForPromises();
      });

      it('exists', () => {
        expect(findFirstActionMenu().exists()).toBe(true);
        expect(findFirstActionMenu().props('icon')).toBe('ellipsis_v');
        expect(findFirstActionMenu().props('textSrOnly')).toBe(true);
        expect(findFirstActionMenu().props('text')).toMatchInterpolatedText('More actions');
      });

      describe('menu items', () => {
        describe('delete file', () => {
          it('exists', () => {
            expect(findActionMenuDelete().exists()).toBe(true);
          });

          it('shows delete file confirmation modal', async () => {
            await findActionMenuDelete().trigger('click');

            expect(showMock).toHaveBeenCalledTimes(1);

            expect(findDeleteFilesModal().text()).toBe(
              'You are about to delete foo-1.0.1.tgz. This is a destructive action that may render your package unusable. Are you sure?',
            );
          });
        });
      });
    });

    describe('when the user can not delete', () => {
      const canDelete = false;

      it('does not exist', async () => {
        createComponent({ canDelete });
        await waitForPromises();

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

  describe('multi select', () => {
    describe('when user can delete', () => {
      it('delete selected button exists & is disabled', async () => {
        createComponent();
        await waitForPromises();

        expect(findDeleteSelectedButton().exists()).toBe(true);
        expect(findDeleteSelectedButton().text()).toMatchInterpolatedText('Delete selected');
        expect(findDeleteSelectedButton().props('disabled')).toBe(true);
      });

      it('checkboxes to select file are visible', async () => {
        createComponent({ resolver: jest.fn().mockResolvedValue(packageFilesQuery()) });
        await waitForPromises();

        expect(findCheckAllCheckbox().exists()).toBe(true);
        expect(findAllRowCheckboxes()).toHaveLength(2);
      });

      it('selecting a checkbox enables delete selected button', async () => {
        createComponent();
        await waitForPromises();

        const first = findAllRowCheckboxes().at(0);

        await first.setChecked(true);

        expect(findDeleteSelectedButton().props('disabled')).toBe(false);
      });

      describe('select all checkbox', () => {
        it('will toggle between selecting all and deselecting all files', async () => {
          const getChecked = () => findAllRowCheckboxes().filter((x) => x.element.checked === true);

          createComponent({ resolver: jest.fn().mockResolvedValue(packageFilesQuery()) });
          await waitForPromises();

          expect(getChecked()).toHaveLength(0);

          await findCheckAllCheckbox().setChecked(true);

          expect(getChecked()).toHaveLength(files.length);

          await findCheckAllCheckbox().setChecked(false);

          expect(getChecked()).toHaveLength(0);
        });

        it('will toggle the indeterminate state when some but not all files are selected', async () => {
          const expectIndeterminateState = (state) =>
            expect(findCheckAllCheckbox().props('indeterminate')).toBe(state);

          createComponent({
            resolver: jest.fn().mockResolvedValue(packageFilesQuery()),
            stubs: { GlFormCheckbox: stubComponent(GlFormCheckbox, { props: ['indeterminate'] }) },
          });
          await waitForPromises();

          expectIndeterminateState(false);

          await findSecondRow().trigger('click');

          expectIndeterminateState(true);

          await findSecondRow().trigger('click');

          expectIndeterminateState(false);

          findCheckAllCheckbox().trigger('click');

          expectIndeterminateState(false);

          await findSecondRow().trigger('click');

          expectIndeterminateState(true);
        });
      });

      it('shows delete modal with single file confirmation text when delete selected is clicked', async () => {
        createComponent();
        await waitForPromises();

        const first = findAllRowCheckboxes().at(0);

        await first.setChecked(true);

        await findDeleteSelectedButton().trigger('click');

        expect(showMock).toHaveBeenCalledTimes(1);

        expect(findDeleteFilesModal().text()).toBe(
          'You are about to delete foo-1.0.1.tgz. This is a destructive action that may render your package unusable. Are you sure?',
        );
      });

      it('shows delete modal with multiple files confirmation text when delete selected is clicked', async () => {
        createComponent({ resolver: jest.fn().mockResolvedValue(packageFilesQuery()) });
        await waitForPromises();

        await findCheckAllCheckbox().setChecked(true);

        await findDeleteSelectedButton().trigger('click');

        expect(showMock).toHaveBeenCalledTimes(1);

        expect(findDeleteFilesModal().text()).toMatchInterpolatedText(
          'You are about to delete 2 assets. This operation is irreversible.',
        );
      });

      describe('emits delete-all-files event', () => {
        it('with right content for last file in package', async () => {
          createComponent({
            resolver: jest.fn().mockResolvedValue(
              packageFilesQuery({
                files: [file],
                pageInfo: {
                  hasNextPage: false,
                },
              }),
            ),
          });
          await waitForPromises();
          const first = findAllRowCheckboxes().at(0);

          await first.setChecked(true);

          await findDeleteSelectedButton().trigger('click');

          expect(showMock).toHaveBeenCalledTimes(0);

          expect(wrapper.emitted('delete-all-files')).toHaveLength(1);
          expect(wrapper.emitted('delete-all-files')[0]).toEqual([
            DELETE_LAST_PACKAGE_FILE_MODAL_CONTENT,
          ]);
        });

        it('with right content for all files in package', async () => {
          createComponent({
            resolver: jest.fn().mockResolvedValue(
              packageFilesQuery({
                pageInfo: {
                  hasNextPage: false,
                },
              }),
            ),
          });
          await waitForPromises();

          await findCheckAllCheckbox().setChecked(true);

          await findDeleteSelectedButton().trigger('click');

          expect(showMock).toHaveBeenCalledTimes(0);

          expect(wrapper.emitted('delete-all-files')).toHaveLength(1);
          expect(wrapper.emitted('delete-all-files')[0]).toEqual([
            DELETE_ALL_PACKAGE_FILES_MODAL_CONTENT,
          ]);
        });
      });
    });

    describe('when user cannot delete', () => {
      const canDelete = false;

      it('delete selected button does not exist', async () => {
        createComponent({ canDelete });
        await waitForPromises();

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

      it('checkboxes to select file are not visible', async () => {
        createComponent({ resolver: jest.fn().mockResolvedValue(packageFilesQuery()), canDelete });
        await waitForPromises();

        expect(findCheckAllCheckbox().exists()).toBe(false);
        expect(findAllRowCheckboxes()).toHaveLength(0);
      });
    });
  });

  describe('deleting a file', () => {
    const doDeleteFile = async () => {
      const first = findAllRowCheckboxes().at(0);

      await first.setChecked(true);

      await findDeleteSelectedButton().trigger('click');

      findDeleteFilesModal().vm.$emit('primary');
    };

    it('confirming on the modal sets the loading state', async () => {
      createComponent();

      await waitForPromises();

      await doDeleteFile();

      await nextTick();

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

    it('confirming on the modal deletes the file and shows a success message', async () => {
      const resolver = jest.fn().mockResolvedValue(packageFilesQuery({ files: [file] }));
      const filesDeleteMutationResolver = jest
        .fn()
        .mockResolvedValue(packageDestroyFilesMutation());
      createComponent({ resolver, filesDeleteMutationResolver });

      await waitForPromises();

      await doDeleteFile();

      await waitForPromises();

      expect(findLoadingIcon().exists()).toBe(false);

      expect(createAlert).toHaveBeenCalledWith(
        expect.objectContaining({
          message: DELETE_PACKAGE_FILE_SUCCESS_MESSAGE,
        }),
      );

      expect(filesDeleteMutationResolver).toHaveBeenCalledWith({
        ids: [file.id],
        projectPath: 'gitlab-test',
      });

      // we are re-fetching the package files, so we expect the resolver to have been called twice
      expect(resolver).toHaveBeenCalledTimes(2);
      expect(resolver).toHaveBeenCalledWith({
        id: '1',
        first: 100,
      });
    });

    describe('errors', () => {
      it('shows an error when the mutation request fails', async () => {
        createComponent({ filesDeleteMutationResolver: jest.fn().mockRejectedValue() });
        await waitForPromises();

        await doDeleteFile();

        await waitForPromises();

        expect(createAlert).toHaveBeenCalledWith(
          expect.objectContaining({
            message: DELETE_PACKAGE_FILE_ERROR_MESSAGE,
          }),
        );
      });

      it('shows an error when the mutation request returns an error payload', async () => {
        createComponent({
          filesDeleteMutationResolver: jest
            .fn()
            .mockResolvedValue(packageDestroyFilesMutationError()),
        });
        await waitForPromises();

        await doDeleteFile();

        await waitForPromises();

        expect(createAlert).toHaveBeenCalledWith(
          expect.objectContaining({
            message: DELETE_PACKAGE_FILE_ERROR_MESSAGE,
          }),
        );
      });
    });
  });

  describe('deleting multiple files', () => {
    const doDeleteFiles = async () => {
      await findCheckAllCheckbox().setChecked(true);

      await findDeleteSelectedButton().trigger('click');

      findDeleteFilesModal().vm.$emit('primary');
    };

    it('confirming on the modal sets the loading state', async () => {
      createComponent();

      await waitForPromises();

      await doDeleteFiles();

      await nextTick();

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

    it('confirming on the modal deletes the file and shows a success message', async () => {
      const resolver = jest.fn().mockResolvedValue(packageFilesQuery());
      const filesDeleteMutationResolver = jest
        .fn()
        .mockResolvedValue(packageDestroyFilesMutation());
      createComponent({ resolver, filesDeleteMutationResolver });

      await waitForPromises();

      await doDeleteFiles();

      await waitForPromises();

      expect(findLoadingIcon().exists()).toBe(false);

      expect(createAlert).toHaveBeenCalledWith(
        expect.objectContaining({
          message: DELETE_PACKAGE_FILES_SUCCESS_MESSAGE,
        }),
      );

      expect(filesDeleteMutationResolver).toHaveBeenCalledWith({
        ids: files.map(({ id }) => id),
        projectPath: 'gitlab-test',
      });

      // we are re-fetching the package files, so we expect the resolver to have been called twice
      expect(resolver).toHaveBeenCalledTimes(2);
      expect(resolver).toHaveBeenCalledWith({
        id: '1',
        first: 100,
      });
    });

    describe('errors', () => {
      it('shows an error when the mutation request fails', async () => {
        const resolver = jest.fn().mockResolvedValue(packageFilesQuery());
        createComponent({ filesDeleteMutationResolver: jest.fn().mockRejectedValue(), resolver });
        await waitForPromises();

        await doDeleteFiles();

        await waitForPromises();

        expect(createAlert).toHaveBeenCalledWith(
          expect.objectContaining({
            message: DELETE_PACKAGE_FILES_ERROR_MESSAGE,
          }),
        );
      });

      it('shows an error when the mutation request returns an error payload', async () => {
        const resolver = jest.fn().mockResolvedValue(packageFilesQuery());
        createComponent({
          filesDeleteMutationResolver: jest
            .fn()
            .mockResolvedValue(packageDestroyFilesMutationError()),
          resolver,
        });
        await waitForPromises();

        await doDeleteFiles();

        await waitForPromises();

        expect(createAlert).toHaveBeenCalledWith(
          expect.objectContaining({
            message: DELETE_PACKAGE_FILES_ERROR_MESSAGE,
          }),
        );
      });
    });
  });

  describe('additional details', () => {
    describe('details toggle button', () => {
      it('exists', async () => {
        createComponent();
        await waitForPromises();

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

      it('is hidden when no details is present', async () => {
        const { ...noShaFile } = file;
        noShaFile.fileSha256 = null;
        noShaFile.fileMd5 = null;
        noShaFile.fileSha1 = null;
        createComponent({
          resolver: jest.fn().mockResolvedValue(packageFilesQuery({ files: [noShaFile] })),
        });
        await waitForPromises();

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

      it('toggles the details row', async () => {
        createComponent();
        await waitForPromises();

        expect(findFirstToggleDetailsButton().props('icon')).toBe('chevron-down');

        findFirstToggleDetailsButton().vm.$emit('click');
        await nextTick();

        expect(findFirstRowShaComponent('sha-256').exists()).toBe(true);
        expect(findFirstToggleDetailsButton().props('icon')).toBe('chevron-up');

        findFirstToggleDetailsButton().vm.$emit('click');
        await nextTick();

        expect(findFirstRowShaComponent('sha-256').exists()).toBe(false);
        expect(findFirstToggleDetailsButton().props('icon')).toBe('chevron-down');
      });
    });

    describe('file shas', () => {
      const showShaFiles = () => {
        findFirstToggleDetailsButton().vm.$emit('click');
        return nextTick();
      };

      it.each`
        selector     | title        | sha
        ${'sha-256'} | ${'SHA-256'} | ${'fileSha256'}
        ${'md5'}     | ${'MD5'}     | ${'fileMd5'}
        ${'sha-1'}   | ${'SHA-1'}   | ${'be93151dc23ac34a82752444556fe79b32c7a1ad'}
      `('has a $title row', async ({ selector, title, sha }) => {
        createComponent();
        await waitForPromises();

        await showShaFiles();

        expect(findFirstRowShaComponent(selector).props()).toMatchObject({
          title,
          sha,
        });
      });

      it('does not display a row when the data is missing', async () => {
        const { ...missingMd5 } = file;
        missingMd5.fileMd5 = null;

        createComponent({
          resolver: jest.fn().mockResolvedValue(packageFilesQuery({ files: [missingMd5] })),
        });
        await waitForPromises();

        await showShaFiles();

        expect(findFirstRowShaComponent('md5').exists()).toBe(false);
      });
    });
  });
});