summaryrefslogtreecommitdiff
path: root/spec/frontend/design_management/pages/index_spec.js
blob: 87531e8b645c337f9a07231fbc524f262b6f7a0a (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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
import { GlEmptyState } from '@gitlab/ui';
import { shallowMount } from '@vue/test-utils';
import Vue, { nextTick } from 'vue';

import VueApollo, { ApolloMutation } from 'vue-apollo';
import VueRouter from 'vue-router';
import VueDraggable from 'vuedraggable';
import createMockApollo from 'helpers/mock_apollo_helper';
import waitForPromises from 'helpers/wait_for_promises';
import { mockTracking, unmockTracking } from 'helpers/tracking_helper';
import permissionsQuery from 'shared_queries/design_management/design_permissions.query.graphql';
import getDesignListQuery from 'shared_queries/design_management/get_design_list.query.graphql';
import DeleteButton from '~/design_management/components/delete_button.vue';
import DesignDestroyer from '~/design_management/components/design_destroyer.vue';
import Design from '~/design_management/components/list/item.vue';
import moveDesignMutation from '~/design_management/graphql/mutations/move_design.mutation.graphql';
import uploadDesignMutation from '~/design_management/graphql/mutations/upload_design.mutation.graphql';
import Index from '~/design_management/pages/index.vue';
import createRouter from '~/design_management/router';
import { DESIGNS_ROUTE_NAME } from '~/design_management/router/constants';
import * as utils from '~/design_management/utils/design_management_utils';
import {
  EXISTING_DESIGN_DROP_MANY_FILES_MESSAGE,
  EXISTING_DESIGN_DROP_INVALID_FILENAME_MESSAGE,
} from '~/design_management/utils/error_messages';
import {
  DESIGN_TRACKING_PAGE_NAME,
  DESIGN_SNOWPLOW_EVENT_TYPES,
} from '~/design_management/utils/tracking';
import createFlash from '~/flash';
import DesignDropzone from '~/vue_shared/components/upload_dropzone/upload_dropzone.vue';
import {
  designListQueryResponse,
  designUploadMutationCreatedResponse,
  designUploadMutationUpdatedResponse,
  permissionsQueryResponse,
  moveDesignMutationResponse,
  reorderedDesigns,
  moveDesignMutationResponseWithErrors,
} from '../mock_data/apollo_mock';

jest.mock('~/flash.js');
const mockPageEl = {
  classList: {
    remove: jest.fn(),
  },
};
jest.spyOn(utils, 'getPageLayoutElement').mockReturnValue(mockPageEl);

const scrollIntoViewMock = jest.fn();
HTMLElement.prototype.scrollIntoView = scrollIntoViewMock;

const router = createRouter();
Vue.use(VueRouter);

const mockDesigns = [
  {
    id: 'design-1',
    image: 'design-1-image',
    filename: 'design-1-name',
    event: 'NONE',
    notesCount: 0,
  },
  {
    id: 'design-2',
    image: 'design-2-image',
    filename: 'design-2-name',
    event: 'NONE',
    notesCount: 1,
  },
  {
    id: 'design-3',
    image: 'design-3-image',
    filename: 'design-3-name',
    event: 'NONE',
    notesCount: 0,
  },
];

const mockVersion = {
  id: 'gid://gitlab/DesignManagement::Version/1',
};

const designToMove = {
  __typename: 'Design',
  id: '2',
  event: 'NONE',
  filename: 'fox_2.jpg',
  notesCount: 2,
  image: 'image-2',
  imageV432x230: 'image-2',
};

describe('Design management index page', () => {
  const registerPath = '/users/sign_up?redirect_to_referer=yes';
  const signInPath = '/users/sign_in?redirect_to_referer=yes';
  let mutate;
  let wrapper;
  let fakeApollo;
  let moveDesignHandler;

  const findDesignCheckboxes = () => wrapper.findAll('.design-checkbox');
  const findSelectAllButton = () => wrapper.find('[data-testid="select-all-designs-button"');
  const findToolbar = () => wrapper.find('.qa-selector-toolbar');
  const findDesignCollectionIsCopying = () =>
    wrapper.find('[data-testid="design-collection-is-copying"');
  const findDeleteButton = () => wrapper.find(DeleteButton);
  const findDropzone = () => wrapper.findAll(DesignDropzone).at(0);
  const dropzoneClasses = () => findDropzone().classes();
  const findDropzoneWrapper = () => wrapper.find('[data-testid="design-dropzone-wrapper"]');
  const findFirstDropzoneWithDesign = () => wrapper.findAll(DesignDropzone).at(1);
  const findDesignsWrapper = () => wrapper.find('[data-testid="designs-root"]');
  const findDesigns = () => wrapper.findAll(Design);
  const draggableAttributes = () => wrapper.find(VueDraggable).vm.$attrs;
  const findDesignUploadButton = () => wrapper.find('[data-testid="design-upload-button"]');
  const findDesignToolbarWrapper = () => wrapper.find('[data-testid="design-toolbar-wrapper"]');

  async function moveDesigns(localWrapper) {
    await waitForPromises();

    localWrapper.find(VueDraggable).vm.$emit('input', reorderedDesigns);
    localWrapper.find(VueDraggable).vm.$emit('change', {
      moved: {
        newIndex: 0,
        element: designToMove,
      },
    });
  }

  function createComponent({
    loading = false,
    allVersions = [],
    designCollection = { designs: mockDesigns, copyState: 'READY' },
    createDesign = true,
    stubs = {},
    mockMutate = jest.fn().mockResolvedValue(),
  } = {}) {
    mutate = mockMutate;
    const $apollo = {
      queries: {
        designCollection: {
          loading,
        },
        permissions: {
          loading,
        },
      },
      mutate,
    };

    wrapper = shallowMount(Index, {
      data() {
        return {
          allVersions,
          designCollection,
          permissions: {
            createDesign,
          },
        };
      },
      mocks: { $apollo },
      router,
      stubs: { DesignDestroyer, ApolloMutation, VueDraggable, ...stubs },
      attachTo: document.body,
      provide: {
        projectPath: 'project-path',
        issueIid: '1',
        registerPath,
        signInPath,
      },
    });
  }

  function createComponentWithApollo({
    moveHandler = jest.fn().mockResolvedValue(moveDesignMutationResponse),
  }) {
    Vue.use(VueApollo);
    moveDesignHandler = moveHandler;

    const requestHandlers = [
      [getDesignListQuery, jest.fn().mockResolvedValue(designListQueryResponse)],
      [permissionsQuery, jest.fn().mockResolvedValue(permissionsQueryResponse)],
      [moveDesignMutation, moveDesignHandler],
    ];

    fakeApollo = createMockApollo(requestHandlers, {}, { addTypename: true });
    wrapper = shallowMount(Index, {
      apolloProvider: fakeApollo,
      router,
      stubs: { VueDraggable },
      provide: {
        registerPath,
        signInPath,
      },
    });
  }

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

  describe('designs', () => {
    it('renders loading icon', () => {
      createComponent({ loading: true });

      expect(wrapper.element).toMatchSnapshot();
    });

    it('renders error', async () => {
      createComponent();

      // setData usage is discouraged. See https://gitlab.com/groups/gitlab-org/-/epics/7330 for details
      // eslint-disable-next-line no-restricted-syntax
      wrapper.setData({ error: true });

      await nextTick();
      expect(wrapper.element).toMatchSnapshot();
    });

    it('renders a toolbar with buttons when there are designs', () => {
      createComponent({ allVersions: [mockVersion] });

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

    it('renders designs list and header with upload button', () => {
      createComponent({ allVersions: [mockVersion] });

      expect(findDesignsWrapper().exists()).toBe(true);
      expect(findDesigns().length).toBe(3);
      expect(findDesignToolbarWrapper().exists()).toBe(true);
      expect(findDesignUploadButton().exists()).toBe(true);
    });

    it('does not render toolbar when there is no permission', () => {
      createComponent({ designs: mockDesigns, allVersions: [mockVersion], createDesign: false });

      expect(findDesignToolbarWrapper().exists()).toBe(false);
      expect(findDesignUploadButton().exists()).toBe(false);
    });

    it('has correct classes applied to design dropzone', () => {
      createComponent({ designs: mockDesigns, allVersions: [mockVersion] });
      expect(dropzoneClasses()).toContain('design-list-item');
      expect(dropzoneClasses()).toContain('design-list-item-new');
    });

    it('has correct classes applied to dropzone wrapper', () => {
      createComponent({ designs: mockDesigns, allVersions: [mockVersion] });
      expect(findDropzoneWrapper().classes()).toEqual([
        'gl-flex-direction-column',
        'col-md-6',
        'col-lg-3',
        'gl-mb-3',
      ]);
    });
  });

  describe('when has no designs', () => {
    beforeEach(() => {
      createComponent({ designCollection: { designs: [], copyState: 'READY' } });
    });

    it('renders design dropzone', async () => {
      await nextTick();
      expect(findDropzone().exists()).toBe(true);
    });

    it('has correct classes applied to design dropzone', () => {
      expect(dropzoneClasses()).not.toContain('design-list-item');
      expect(dropzoneClasses()).not.toContain('design-list-item-new');
    });

    it('has correct classes applied to dropzone wrapper', () => {
      expect(findDropzoneWrapper().classes()).toEqual(['col-12']);
    });

    it('does not render a toolbar with buttons', async () => {
      await nextTick();
      expect(findToolbar().exists()).toBe(false);
    });
  });

  describe('handling design collection copy state', () => {
    it.each`
      copyState        | isRendered | description
      ${'IN_PROGRESS'} | ${true}    | ${'renders'}
      ${'READY'}       | ${false}   | ${'does not render'}
      ${'ERROR'}       | ${false}   | ${'does not render'}
    `(
      '$description the copying message if design collection copyState is $copyState',
      ({ copyState, isRendered }) => {
        createComponent({ designCollection: { designs: [], copyState } });
        expect(findDesignCollectionIsCopying().exists()).toBe(isRendered);
      },
    );
  });

  describe('uploading designs', () => {
    it('calls mutation on upload', async () => {
      createComponent({ stubs: { GlEmptyState } });

      const mutationVariables = {
        update: expect.anything(),
        context: {
          hasUpload: true,
        },
        mutation: uploadDesignMutation,
        variables: {
          files: [{ name: 'test' }],
          projectPath: 'project-path',
          iid: '1',
        },
        optimisticResponse: {
          __typename: 'Mutation',
          designManagementUpload: {
            __typename: 'DesignManagementUploadPayload',
            designs: [
              {
                __typename: 'Design',
                id: expect.anything(),
                currentUserTodos: {
                  __typename: 'TodoConnection',
                  nodes: [],
                },
                image: '',
                imageV432x230: '',
                filename: 'test',
                fullPath: '',
                event: 'NONE',
                notesCount: 0,
                diffRefs: {
                  __typename: 'DiffRefs',
                  baseSha: '',
                  startSha: '',
                  headSha: '',
                },
                discussions: {
                  __typename: 'DesignDiscussion',
                  nodes: [],
                },
                versions: {
                  __typename: 'DesignVersionConnection',
                  nodes: {
                    __typename: 'DesignVersion',
                    id: expect.anything(),
                    sha: expect.anything(),
                    createdAt: '',
                    author: {
                      __typename: 'UserCore',
                      id: expect.anything(),
                      name: '',
                      avatarUrl: '',
                    },
                  },
                },
              },
            ],
            skippedDesigns: [],
            errors: [],
          },
        },
      };

      await nextTick();
      findDropzone().vm.$emit('change', [{ name: 'test' }]);
      expect(mutate).toHaveBeenCalledWith(mutationVariables);
      expect(wrapper.vm.filesToBeSaved).toEqual([{ name: 'test' }]);
      expect(wrapper.vm.isSaving).toBeTruthy();
      expect(dropzoneClasses()).toContain('design-list-item');
      expect(dropzoneClasses()).toContain('design-list-item-new');
    });

    it('sets isSaving', async () => {
      createComponent();

      const uploadDesign = wrapper.vm.onUploadDesign([
        {
          name: 'test',
        },
      ]);

      expect(wrapper.vm.isSaving).toBe(true);

      await uploadDesign;
      expect(wrapper.vm.isSaving).toBe(false);
    });

    it('updates state appropriately after upload complete', async () => {
      createComponent({ stubs: { GlEmptyState } });
      // setData usage is discouraged. See https://gitlab.com/groups/gitlab-org/-/epics/7330 for details
      // eslint-disable-next-line no-restricted-syntax
      wrapper.setData({ filesToBeSaved: [{ name: 'test' }] });

      wrapper.vm.onUploadDesignDone(designUploadMutationCreatedResponse);
      await nextTick();

      expect(wrapper.vm.filesToBeSaved).toEqual([]);
      expect(wrapper.vm.isSaving).toBeFalsy();
      expect(wrapper.vm.isLatestVersion).toBe(true);
    });

    it('updates state appropriately after upload error', async () => {
      createComponent({ stubs: { GlEmptyState } });
      // setData usage is discouraged. See https://gitlab.com/groups/gitlab-org/-/epics/7330 for details
      // eslint-disable-next-line no-restricted-syntax
      wrapper.setData({ filesToBeSaved: [{ name: 'test' }] });

      wrapper.vm.onUploadDesignError();
      await nextTick();
      expect(wrapper.vm.filesToBeSaved).toEqual([]);
      expect(wrapper.vm.isSaving).toBeFalsy();
      expect(createFlash).toHaveBeenCalled();
    });

    it('does not call mutation if createDesign is false', () => {
      createComponent({ createDesign: false });

      wrapper.vm.onUploadDesign([]);

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

    describe('upload count limit', () => {
      const MAXIMUM_FILE_UPLOAD_LIMIT = 10;

      it('does not warn when the max files are uploaded', () => {
        createComponent();

        wrapper.vm.onUploadDesign(new Array(MAXIMUM_FILE_UPLOAD_LIMIT).fill(mockDesigns[0]));

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

      it('warns when too many files are uploaded', () => {
        createComponent();

        wrapper.vm.onUploadDesign(new Array(MAXIMUM_FILE_UPLOAD_LIMIT + 1).fill(mockDesigns[0]));

        expect(createFlash).toHaveBeenCalled();
      });
    });

    it('flashes warning if designs are skipped', async () => {
      createComponent({
        mockMutate: () =>
          Promise.resolve({
            data: { designManagementUpload: { skippedDesigns: [{ filename: 'test.jpg' }] } },
          }),
      });

      const uploadDesign = wrapper.vm.onUploadDesign([
        {
          name: 'test',
        },
      ]);

      await uploadDesign;
      expect(createFlash).toHaveBeenCalledTimes(1);
      expect(createFlash).toHaveBeenCalledWith({
        message: 'Upload skipped. test.jpg did not change.',
        types: 'warning',
      });
    });

    describe('dragging onto an existing design', () => {
      let mockMutate;
      beforeEach(() => {
        mockMutate = jest.fn().mockResolvedValue();
        createComponent({ designs: mockDesigns, allVersions: [mockVersion], mockMutate });
      });

      it('uploads designs with valid upload', () => {
        const mockUploadPayload = [
          {
            name: mockDesigns[0].filename,
          },
        ];

        const designDropzone = findFirstDropzoneWithDesign();
        designDropzone.vm.$emit('change', mockUploadPayload);

        const [{ mutation, variables }] = mockMutate.mock.calls[0];
        expect(mutation).toBe(uploadDesignMutation);
        expect(variables).toStrictEqual({
          files: mockUploadPayload,
          iid: '1',
          projectPath: 'project-path',
        });
      });

      it.each`
        description             | eventPayload                              | message
        ${'> 1 file'}           | ${[{ name: 'test' }, { name: 'test-2' }]} | ${EXISTING_DESIGN_DROP_MANY_FILES_MESSAGE}
        ${'different filename'} | ${[{ name: 'wrong-name' }]}               | ${EXISTING_DESIGN_DROP_INVALID_FILENAME_MESSAGE}
      `('calls createFlash when upload has $description', ({ eventPayload, message }) => {
        const designDropzone = findFirstDropzoneWithDesign();
        designDropzone.vm.$emit('change', eventPayload);

        expect(createFlash).toHaveBeenCalledTimes(1);
        expect(createFlash).toHaveBeenCalledWith({ message });
      });
    });

    describe('tracking', () => {
      let trackingSpy;

      beforeEach(() => {
        trackingSpy = mockTracking('_category_', undefined, jest.spyOn);

        createComponent({ stubs: { GlEmptyState } });
      });

      afterEach(() => {
        unmockTracking();
      });

      it('tracks design creation', () => {
        wrapper.vm.onUploadDesignDone(designUploadMutationCreatedResponse);

        expect(trackingSpy).toHaveBeenCalledTimes(1);
        expect(trackingSpy).toHaveBeenCalledWith(
          DESIGN_TRACKING_PAGE_NAME,
          DESIGN_SNOWPLOW_EVENT_TYPES.CREATE_DESIGN,
        );
      });

      it('tracks design modification', () => {
        wrapper.vm.onUploadDesignDone(designUploadMutationUpdatedResponse);

        expect(trackingSpy).toHaveBeenCalledTimes(1);
        expect(trackingSpy).toHaveBeenCalledWith(
          DESIGN_TRACKING_PAGE_NAME,
          DESIGN_SNOWPLOW_EVENT_TYPES.UPDATE_DESIGN,
        );
      });
    });
  });

  describe('on latest version when has designs', () => {
    beforeEach(() => {
      createComponent({ designs: mockDesigns, allVersions: [mockVersion] });
    });

    it('renders design checkboxes', () => {
      expect(findDesignCheckboxes()).toHaveLength(mockDesigns.length);
    });

    it('renders toolbar buttons', () => {
      expect(findToolbar().exists()).toBe(true);
      expect(findToolbar().isVisible()).toBe(true);
    });

    it('adds two designs to selected designs when their checkboxes are checked', async () => {
      findDesignCheckboxes().at(0).trigger('click');

      await nextTick();
      findDesignCheckboxes().at(1).trigger('click');

      await nextTick();
      expect(findDeleteButton().exists()).toBe(true);
      expect(findSelectAllButton().text()).toBe('Deselect all');

      findDeleteButton().vm.$emit('delete-selected-designs');

      const [{ variables }] = mutate.mock.calls[0];
      expect(variables.filenames).toStrictEqual([mockDesigns[0].filename, mockDesigns[1].filename]);
    });

    it('adds all designs to selected designs when Select All button is clicked', async () => {
      findSelectAllButton().vm.$emit('click');

      await nextTick();
      expect(findDeleteButton().props().hasSelectedDesigns).toBe(true);
      expect(findSelectAllButton().text()).toBe('Deselect all');
      expect(wrapper.vm.selectedDesigns).toEqual(mockDesigns.map((design) => design.filename));
    });

    it('removes all designs from selected designs when at least one design was selected', async () => {
      findDesignCheckboxes().at(0).trigger('click');
      await nextTick();

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

      expect(findDeleteButton().props().hasSelectedDesigns).toBe(false);
      expect(findSelectAllButton().text()).toBe('Select all');
      expect(wrapper.vm.selectedDesigns).toEqual([]);
    });
  });

  it('on latest version when has no designs toolbar buttons are invisible', () => {
    createComponent({
      designCollection: { designs: [], copyState: 'READY' },
      allVersions: [mockVersion],
    });
    expect(findToolbar().isVisible()).toBe(false);
  });

  describe('on non-latest version', () => {
    beforeEach(() => {
      createComponent({ allVersions: [mockVersion] });
    });

    it('does not render design checkboxes', async () => {
      await router.replace({
        name: DESIGNS_ROUTE_NAME,
        query: {
          version: '2',
        },
      });
      expect(findDesignCheckboxes()).toHaveLength(0);
    });

    it('does not render Delete selected button', () => {
      expect(findDeleteButton().exists()).toBe(false);
    });

    it('does not render Select All button', () => {
      expect(findSelectAllButton().exists()).toBe(false);
    });
  });

  describe('pasting a design', () => {
    let event;
    let mockMutate;
    beforeEach(() => {
      mockMutate = jest.fn().mockResolvedValue({});
      createComponent({ designs: mockDesigns, allVersions: [mockVersion], mockMutate });

      event = new Event('paste');
      event.clipboardData = {
        files: [{ name: 'image.png', type: 'image/png' }],
        getData: () => 'test.png',
      };
    });

    it('does not upload designs if designs wrapper is not hovered', () => {
      document.dispatchEvent(event);

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

    it('does not upload designs if designs wrapper is destroyed', () => {
      findDesignsWrapper().trigger('mouseenter');

      wrapper.destroy();

      document.dispatchEvent(event);

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

    describe('when designs wrapper is hovered', () => {
      let realDateNow;
      const today = () => new Date('2020-12-25');
      beforeAll(() => {
        realDateNow = Date.now;
        global.Date.now = today;
      });

      afterAll(() => {
        global.Date.now = realDateNow;
      });

      beforeEach(() => {
        findDesignsWrapper().trigger('mouseenter');
      });

      it('uploads design with valid paste', () => {
        document.dispatchEvent(event);

        const [{ mutation, variables }] = mockMutate.mock.calls[0];
        expect(mutation).toBe(uploadDesignMutation);
        expect(variables).toStrictEqual({
          files: expect.any(Array),
          iid: '1',
          projectPath: 'project-path',
        });
        expect(variables.files).toEqual(event.clipboardData.files.map((f) => new File([f], '')));
      });

      it('display original file name', () => {
        event.clipboardData.files = [new File([new Blob()], 'test.png', { type: 'image/png' })];
        document.dispatchEvent(event);

        const [{ mutation, variables }] = mockMutate.mock.calls[0];
        expect(mutation).toBe(uploadDesignMutation);
        expect(variables).toStrictEqual({
          files: expect.any(Array),
          iid: '1',
          projectPath: 'project-path',
        });
        expect(variables.files[0].name).toEqual('test.png');
      });

      it('renames a design if it has an image.png filename', () => {
        event.clipboardData.getData = () => 'image.png';
        document.dispatchEvent(event);

        const [{ mutation, variables }] = mockMutate.mock.calls[0];
        expect(mutation).toBe(uploadDesignMutation);
        expect(variables).toStrictEqual({
          files: expect.any(Array),
          iid: '1',
          projectPath: 'project-path',
        });
        expect(variables.files[0].name).toEqual(`design_${Date.now()}.png`);
      });

      it('does not call upload with invalid paste', () => {
        event.clipboardData = {
          items: [{ type: 'text/plain' }, { type: 'text' }],
          files: [],
        };

        document.dispatchEvent(event);

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

      it('removes onPaste listener after mouseleave event', async () => {
        findDesignsWrapper().trigger('mouseleave');
        document.dispatchEvent(event);

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

  describe('when navigating', () => {
    it('should trigger a scrollIntoView method if designs route is detected', async () => {
      router.replace({
        path: '/designs',
      });
      createComponent({ loading: true });

      await nextTick();
      expect(scrollIntoViewMock).toHaveBeenCalled();
    });
  });

  describe('with mocked Apollo client', () => {
    it('has a design with id 1 as a first one', async () => {
      createComponentWithApollo({});
      await waitForPromises();

      expect(findDesigns()).toHaveLength(3);
      expect(findDesigns().at(0).props('id')).toBe('1');
    });

    it('calls a mutation with correct parameters and reorders designs', async () => {
      createComponentWithApollo({});

      await moveDesigns(wrapper);

      expect(moveDesignHandler).toHaveBeenCalled();

      await waitForPromises();

      expect(findDesigns().at(0).props('id')).toBe('2');
    });

    it('prevents reordering when reorderDesigns mutation is in progress', async () => {
      createComponentWithApollo({});
      await moveDesigns(wrapper);

      expect(draggableAttributes().disabled).toBe(true);

      await waitForPromises();

      expect(draggableAttributes().disabled).toBe(false);
    });

    it('displays flash if mutation had a recoverable error', async () => {
      createComponentWithApollo({
        moveHandler: jest.fn().mockResolvedValue(moveDesignMutationResponseWithErrors),
      });

      await moveDesigns(wrapper);
      await waitForPromises();

      expect(createFlash).toHaveBeenCalledWith({ message: 'Houston, we have a problem' });
    });

    it('displays flash if mutation had a non-recoverable error', async () => {
      createComponentWithApollo({
        moveHandler: jest.fn().mockRejectedValue('Error'),
      });

      await moveDesigns(wrapper);
      await waitForPromises();

      expect(createFlash).toHaveBeenCalledWith({
        message: 'Something went wrong when reordering designs. Please try again',
      });
    });
  });
});