summaryrefslogtreecommitdiff
path: root/spec/frontend/issues/show/components/description_spec.js
blob: da51372dd3ddecb64f2df7b6683c96fff36b6b63 (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
import $ from 'jquery';
import Vue, { nextTick } from 'vue';
import VueApollo from 'vue-apollo';
import { GlModal } from '@gitlab/ui';
import getIssueDetailsQuery from 'ee_else_ce/work_items/graphql/get_issue_details.query.graphql';
import setWindowLocation from 'helpers/set_window_location_helper';
import { stubComponent } from 'helpers/stub_component';
import { TEST_HOST } from 'helpers/test_constants';
import { mockTracking } from 'helpers/tracking_helper';
import createMockApollo from 'helpers/mock_apollo_helper';
import waitForPromises from 'helpers/wait_for_promises';
import { shallowMountExtended } from 'helpers/vue_test_utils_helper';
import { createAlert } from '~/flash';
import Description from '~/issues/show/components/description.vue';
import eventHub from '~/issues/show/event_hub';
import { updateHistory } from '~/lib/utils/url_utility';
import workItemQuery from '~/work_items/graphql/work_item.query.graphql';
import createWorkItemMutation from '~/work_items/graphql/create_work_item.mutation.graphql';
import workItemTypesQuery from '~/work_items/graphql/project_work_item_types.query.graphql';
import TaskList from '~/task_list';
import WorkItemDetailModal from '~/work_items/components/work_item_detail_modal.vue';
import { TRACKING_CATEGORY_SHOW } from '~/work_items/constants';
import { renderGFM } from '~/behaviors/markdown/render_gfm';
import {
  createWorkItemMutationErrorResponse,
  createWorkItemMutationResponse,
  getIssueDetailsResponse,
  projectWorkItemTypesQueryResponse,
} from 'jest/work_items/mock_data';
import {
  descriptionProps as initialProps,
  descriptionHtmlWithList,
  descriptionHtmlWithCheckboxes,
  descriptionHtmlWithTask,
} from '../mock_data/mock_data';

jest.mock('~/flash');
jest.mock('~/lib/utils/url_utility', () => ({
  ...jest.requireActual('~/lib/utils/url_utility'),
  updateHistory: jest.fn(),
}));
jest.mock('~/task_list');
jest.mock('~/behaviors/markdown/render_gfm');

const mockSpriteIcons = '/icons.svg';
const showModal = jest.fn();
const hideModal = jest.fn();
const showDetailsModal = jest.fn();
const $toast = {
  show: jest.fn(),
};

const issueDetailsResponse = getIssueDetailsResponse();
const workItemQueryResponse = {
  data: {
    workItem: null,
  },
};

const queryHandler = jest.fn().mockResolvedValue(workItemQueryResponse);
const workItemTypesQueryHandler = jest.fn().mockResolvedValue(projectWorkItemTypesQueryResponse);

describe('Description component', () => {
  let wrapper;
  let originalGon;

  Vue.use(VueApollo);

  const findGfmContent = () => wrapper.find('[data-testid="gfm-content"]');
  const findTextarea = () => wrapper.find('[data-testid="textarea"]');
  const findListItems = () => findGfmContent().findAll('ul > li');
  const findTaskActionButtons = () => wrapper.findAll('.task-list-item-actions');
  const findTaskLink = () => wrapper.find('a.gfm-issue');
  const findModal = () => wrapper.findComponent(GlModal);
  const findWorkItemDetailModal = () => wrapper.findComponent(WorkItemDetailModal);

  function createComponent({
    props = {},
    provide,
    issueDetailsQueryHandler = jest.fn().mockResolvedValue(issueDetailsResponse),
    createWorkItemMutationHandler,
    ...options
  } = {}) {
    wrapper = shallowMountExtended(Description, {
      propsData: {
        issueId: 1,
        issueIid: 1,
        ...initialProps,
        ...props,
      },
      provide: {
        fullPath: 'gitlab-org/gitlab-test',
        hasIterationsFeature: true,
        ...provide,
      },
      apolloProvider: createMockApollo([
        [workItemQuery, queryHandler],
        [workItemTypesQuery, workItemTypesQueryHandler],
        [getIssueDetailsQuery, issueDetailsQueryHandler],
        [createWorkItemMutation, createWorkItemMutationHandler],
      ]),
      mocks: {
        $toast,
      },
      stubs: {
        GlModal: stubComponent(GlModal, {
          methods: {
            show: showModal,
            hide: hideModal,
          },
        }),
        WorkItemDetailModal: stubComponent(WorkItemDetailModal, {
          methods: {
            show: showDetailsModal,
          },
        }),
      },
      ...options,
    });
  }

  beforeEach(() => {
    originalGon = window.gon;
    window.gon = { sprite_icons: mockSpriteIcons };

    setWindowLocation(TEST_HOST);

    if (!document.querySelector('.issuable-meta')) {
      const metaData = document.createElement('div');
      metaData.classList.add('issuable-meta');
      metaData.innerHTML =
        '<div class="flash-container"></div><span id="task_status"></span><span id="task_status_short"></span>';

      document.body.appendChild(metaData);
    }
  });

  afterAll(() => {
    window.gon = originalGon;

    $('.issuable-meta .flash-container').remove();
  });

  it('doesnt animate first description changes', async () => {
    createComponent();
    await wrapper.setProps({
      descriptionHtml: 'changed',
    });

    expect(findGfmContent().classes()).not.toContain('issue-realtime-pre-pulse');
  });

  it('animates description changes on live update', async () => {
    createComponent();
    await wrapper.setProps({
      descriptionHtml: 'changed',
    });

    expect(findGfmContent().classes()).not.toContain('issue-realtime-pre-pulse');

    await wrapper.setProps({
      descriptionHtml: 'changed second time',
    });

    expect(findGfmContent().classes()).toContain('issue-realtime-pre-pulse');

    await jest.runOnlyPendingTimers();

    expect(findGfmContent().classes()).toContain('issue-realtime-trigger-pulse');
  });

  it('applies syntax highlighting and math when description changed', async () => {
    createComponent();

    await wrapper.setProps({
      descriptionHtml: 'changed',
    });

    expect(findGfmContent().exists()).toBe(true);
    expect(renderGFM).toHaveBeenCalled();
  });

  it('sets data-update-url', () => {
    createComponent();
    expect(findTextarea().attributes('data-update-url')).toBe(TEST_HOST);
  });

  describe('TaskList', () => {
    beforeEach(() => {
      TaskList.mockClear();
    });

    it('re-inits the TaskList when description changed', () => {
      createComponent({
        props: {
          issuableType: 'issuableType',
        },
      });
      wrapper.setProps({
        descriptionHtml: 'changed',
      });

      expect(TaskList).toHaveBeenCalled();
    });

    it('does not re-init the TaskList when canUpdate is false', async () => {
      createComponent({
        props: {
          issuableType: 'issuableType',
          canUpdate: false,
        },
      });
      wrapper.setProps({
        descriptionHtml: 'changed',
      });

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

    it('calls with issuableType dataType', () => {
      createComponent({
        props: {
          issuableType: 'issuableType',
        },
      });
      wrapper.setProps({
        descriptionHtml: 'changed',
      });

      expect(TaskList).toHaveBeenCalledWith({
        dataType: 'issuableType',
        fieldName: 'description',
        selector: '.detail-page-description',
        onUpdate: expect.any(Function),
        onSuccess: expect.any(Function),
        onError: expect.any(Function),
        lockVersion: 0,
      });
    });
  });

  describe('taskStatus', () => {
    it('adds full taskStatus', async () => {
      createComponent({
        props: {
          taskStatus: '1 of 1',
        },
      });
      await nextTick();

      expect(document.querySelector('.issuable-meta #task_status').textContent.trim()).toBe(
        '1 of 1',
      );
    });

    it('adds short taskStatus', async () => {
      createComponent({
        props: {
          taskStatus: '1 of 1',
        },
      });
      await nextTick();

      expect(document.querySelector('.issuable-meta #task_status_short').textContent.trim()).toBe(
        '1/1 checklist item',
      );
    });

    it('clears task status text when no tasks are present', async () => {
      createComponent({
        props: {
          taskStatus: '0 of 0',
        },
      });

      await nextTick();

      expect(document.querySelector('.issuable-meta #task_status').textContent.trim()).toBe('');
    });
  });

  describe('with list', () => {
    beforeEach(async () => {
      createComponent({
        props: {
          descriptionHtml: descriptionHtmlWithList,
        },
        attachTo: document.body,
      });
      await nextTick();
    });

    it('shows list items', () => {
      expect(findListItems()).toHaveLength(3);
    });

    it('shows list items drag icons', () => {
      const dragIcon = findListItems().at(0).find('.drag-icon');

      expect(dragIcon.classes()).toEqual(
        expect.arrayContaining(['s14', 'gl-icon', 'gl-cursor-grab', 'gl-opacity-0']),
      );
      expect(dragIcon.attributes()).toMatchObject({
        'aria-hidden': 'true',
        role: 'img',
      });
      expect(dragIcon.find('use').attributes()).toEqual({
        href: `${mockSpriteIcons}#grip`,
      });
    });
  });

  describe('empty description', () => {
    beforeEach(() => {
      createComponent({
        props: {
          descriptionHtml: '',
        },
      });
      return nextTick();
    });

    it('renders without error', () => {
      expect(findTaskActionButtons()).toHaveLength(0);
    });
  });

  describe('description with checkboxes', () => {
    beforeEach(() => {
      createComponent({
        props: {
          descriptionHtml: descriptionHtmlWithCheckboxes,
        },
      });
      return nextTick();
    });

    it('renders a list of hidden buttons corresponding to checkboxes in description HTML', () => {
      expect(findTaskActionButtons()).toHaveLength(3);
    });

    it('does not show a modal by default', () => {
      expect(findModal().exists()).toBe(false);
    });

    it('shows toast after delete success', async () => {
      const newDesc = 'description';
      findWorkItemDetailModal().vm.$emit('workItemDeleted', newDesc);

      expect(wrapper.emitted('updateDescription')).toEqual([[newDesc]]);
      expect($toast.show).toHaveBeenCalledWith('Task deleted');
    });
  });

  describe('task list item actions', () => {
    describe('converting the task list item to a task', () => {
      describe('when successful', () => {
        let createWorkItemMutationHandler;

        beforeEach(async () => {
          createWorkItemMutationHandler = jest
            .fn()
            .mockResolvedValue(createWorkItemMutationResponse);
          const descriptionText = `Tasks

1. [ ] item 1
   1. [ ] item 2

      paragraph text

      1. [ ] item 3
   1. [ ] item 4;`;
          createComponent({
            props: { descriptionText },
            createWorkItemMutationHandler,
          });
          await waitForPromises();

          eventHub.$emit('convert-task-list-item', '4:4-8:19');
          await waitForPromises();
        });

        it('emits an event to update the description with the deleted task list item omitted', () => {
          const newDescriptionText = `Tasks

1. [ ] item 1
   1. [ ] item 3
   1. [ ] item 4;`;

          expect(wrapper.emitted('saveDescription')).toEqual([[newDescriptionText]]);
        });

        it('calls a mutation to create a task', () => {
          const {
            confidential,
            iteration,
            milestone,
          } = issueDetailsResponse.data.workspace.issuable;
          expect(createWorkItemMutationHandler).toHaveBeenCalledWith({
            input: {
              confidential,
              description: '\nparagraph text\n',
              hierarchyWidget: {
                parentId: 'gid://gitlab/WorkItem/1',
              },
              iterationWidget: {
                iterationId: IS_EE ? iteration.id : null,
              },
              milestoneWidget: {
                milestoneId: milestone.id,
              },
              projectPath: 'gitlab-org/gitlab-test',
              title: 'item 2',
              workItemTypeId: 'gid://gitlab/WorkItems::Type/3',
            },
          });
        });

        it('shows a toast to confirm the creation of the task', () => {
          expect($toast.show).toHaveBeenCalledWith('Converted to task', expect.any(Object));
        });
      });

      describe('when unsuccessful', () => {
        beforeEach(async () => {
          createComponent({
            props: { descriptionText: 'description' },
            createWorkItemMutationHandler: jest
              .fn()
              .mockResolvedValue(createWorkItemMutationErrorResponse),
          });
          await waitForPromises();

          eventHub.$emit('convert-task-list-item', '1:1-1:11');
          await waitForPromises();
        });

        it('shows an alert with an error message', () => {
          expect(createAlert).toHaveBeenCalledWith({
            message: 'Something went wrong when creating task. Please try again.',
            error: new Error('an error'),
            captureError: true,
          });
        });
      });
    });

    describe('deleting the task list item', () => {
      it('emits an event to update the description with the deleted task list item', () => {
        const descriptionText = `Tasks

1. [ ] item 1
   1. [ ] item 2
      1. [ ] item 3
   1. [ ] item 4;`;
        const newDescriptionText = `Tasks

1. [ ] item 1
   1. [ ] item 3
   1. [ ] item 4;`;
        createComponent({
          props: { descriptionText },
        });

        eventHub.$emit('delete-task-list-item', '4:4-5:19');

        expect(wrapper.emitted('saveDescription')).toEqual([[newDescriptionText]]);
      });
    });
  });

  describe('work items detail', () => {
    describe('when opening and closing', () => {
      beforeEach(() => {
        createComponent({
          props: {
            descriptionHtml: descriptionHtmlWithTask,
          },
        });
        return nextTick();
      });

      it('opens when task button is clicked', async () => {
        await findTaskLink().trigger('click');

        expect(showDetailsModal).toHaveBeenCalled();
        expect(updateHistory).toHaveBeenCalledWith({
          url: `${TEST_HOST}/?work_item_id=2`,
          replace: true,
        });
      });

      it('closes from an open state', async () => {
        await findTaskLink().trigger('click');

        findWorkItemDetailModal().vm.$emit('close');
        await nextTick();

        expect(updateHistory).toHaveBeenLastCalledWith({
          url: `${TEST_HOST}/`,
          replace: true,
        });
      });

      it('tracks when opened', async () => {
        const trackingSpy = mockTracking(undefined, wrapper.element, jest.spyOn);

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

        expect(trackingSpy).toHaveBeenCalledWith(
          TRACKING_CATEGORY_SHOW,
          'viewed_work_item_from_modal',
          {
            category: TRACKING_CATEGORY_SHOW,
            label: 'work_item_view',
            property: 'type_task',
          },
        );
      });
    });

    describe('when url query `work_item_id` exists', () => {
      it.each`
        behavior           | workItemId     | modalOpened
        ${'opens'}         | ${'2'}         | ${1}
        ${'does not open'} | ${'123'}       | ${0}
        ${'does not open'} | ${'123e'}      | ${0}
        ${'does not open'} | ${'12e3'}      | ${0}
        ${'does not open'} | ${'1e23'}      | ${0}
        ${'does not open'} | ${'x'}         | ${0}
        ${'does not open'} | ${'undefined'} | ${0}
      `(
        '$behavior when url contains `work_item_id=$workItemId`',
        async ({ workItemId, modalOpened }) => {
          setWindowLocation(`?work_item_id=${workItemId}`);

          createComponent({
            props: { descriptionHtml: descriptionHtmlWithTask },
          });

          expect(showDetailsModal).toHaveBeenCalledTimes(modalOpened);
        },
      );
    });
  });

  describe('when hovering task links', () => {
    beforeEach(() => {
      createComponent({
        props: {
          descriptionHtml: descriptionHtmlWithTask,
        },
      });
      return nextTick();
    });

    it('prefetches work item detail after work item link is hovered for 150ms', async () => {
      await findTaskLink().trigger('mouseover');
      jest.advanceTimersByTime(150);
      await waitForPromises();

      expect(queryHandler).toHaveBeenCalledWith({
        id: 'gid://gitlab/WorkItem/2',
      });
    });

    it('does not work item detail after work item link is hovered for less than 150ms', async () => {
      await findTaskLink().trigger('mouseover');
      await findTaskLink().trigger('mouseout');
      jest.advanceTimersByTime(150);
      await waitForPromises();

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