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

work_item_note_spec.js « notes « components « work_items « frontend « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: c5d1decfb42de39add88942bb2c192f1c233ccfe (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
import { shallowMount } from '@vue/test-utils';
import Vue, { nextTick } from 'vue';
import VueApollo from 'vue-apollo';
import { GlAvatarLink } from '@gitlab/ui';
import mockApollo from 'helpers/mock_apollo_helper';
import waitForPromises from 'helpers/wait_for_promises';
import { updateDraft, clearDraft } from '~/lib/utils/autosave';
import EditedAt from '~/issues/show/components/edited.vue';
import WorkItemNote from '~/work_items/components/notes/work_item_note.vue';
import WorkItemNoteAwardsList from '~/work_items/components/notes/work_item_note_awards_list.vue';
import TimelineEntryItem from '~/vue_shared/components/notes/timeline_entry_item.vue';
import NoteBody from '~/work_items/components/notes/work_item_note_body.vue';
import NoteHeader from '~/notes/components/note_header.vue';
import NoteActions from '~/work_items/components/notes/work_item_note_actions.vue';
import WorkItemCommentForm from '~/work_items/components/notes/work_item_comment_form.vue';
import updateWorkItemNoteMutation from '~/work_items/graphql/notes/update_work_item_note.mutation.graphql';
import updateWorkItemMutation from '~/work_items/graphql/update_work_item.mutation.graphql';
import workItemByIidQuery from '~/work_items/graphql/work_item_by_iid.query.graphql';
import {
  mockAssignees,
  mockWorkItemCommentNote,
  updateWorkItemMutationResponse,
  workItemByIidResponseFactory,
  workItemQueryResponse,
  mockWorkItemCommentNoteByContributor,
  mockWorkItemCommentByMaintainer,
} from 'jest/work_items/mock_data';
import { i18n, TRACKING_CATEGORY_SHOW } from '~/work_items/constants';
import { mockTracking } from 'helpers/tracking_helper';

Vue.use(VueApollo);
jest.mock('~/lib/utils/autosave');

describe('Work Item Note', () => {
  let wrapper;
  const updatedNoteText = '# Some title';
  const updatedNoteBody = '<h1 data-sourcepos="1:1-1:12" dir="auto">Some title</h1>';
  const mockWorkItemId = workItemQueryResponse.data.workItem.id;

  const mockWorkItemByDifferentUser = {
    data: {
      workItem: {
        ...workItemQueryResponse.data.workItem,
        author: {
          avatarUrl:
            'http://127.0.0.1:3000/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon',
          id: 'gid://gitlab/User/2',
          name: 'User 1',
          username: 'user1',
          webUrl: 'http://127.0.0.1:3000/user1',
          __typename: 'UserCore',
        },
      },
    },
  };

  const successHandler = jest.fn().mockResolvedValue({
    data: {
      updateNote: {
        errors: [],
        note: {
          ...mockWorkItemCommentNote,
          body: updatedNoteText,
          bodyHtml: updatedNoteBody,
        },
      },
    },
  });

  const workItemResponseHandler = jest.fn().mockResolvedValue(workItemByIidResponseFactory());
  const workItemByAuthoredByDifferentUser = jest
    .fn()
    .mockResolvedValue(mockWorkItemByDifferentUser);

  const updateWorkItemMutationSuccessHandler = jest
    .fn()
    .mockResolvedValue(updateWorkItemMutationResponse);

  const errorHandler = jest.fn().mockRejectedValue('Oops');

  const findAwardsList = () => wrapper.findComponent(WorkItemNoteAwardsList);
  const findTimelineEntryItem = () => wrapper.findComponent(TimelineEntryItem);
  const findNoteHeader = () => wrapper.findComponent(NoteHeader);
  const findNoteBody = () => wrapper.findComponent(NoteBody);
  const findNoteActions = () => wrapper.findComponent(NoteActions);
  const findCommentForm = () => wrapper.findComponent(WorkItemCommentForm);
  const findEditedAt = () => wrapper.findComponent(EditedAt);
  const findNoteWrapper = () => wrapper.find('[data-testid="note-wrapper"]');

  const createComponent = ({
    note = mockWorkItemCommentNote,
    isFirstNote = false,
    updateNoteMutationHandler = successHandler,
    workItemId = mockWorkItemId,
    updateWorkItemMutationHandler = updateWorkItemMutationSuccessHandler,
    assignees = mockAssignees,
    workItemByIidResponseHandler = workItemResponseHandler,
  } = {}) => {
    wrapper = shallowMount(WorkItemNote, {
      provide: {
        fullPath: 'test-project-path',
      },
      propsData: {
        workItemId,
        workItemIid: '1',
        note,
        isFirstNote,
        workItemType: 'Task',
        markdownPreviewPath: '/group/project/preview_markdown?target_type=WorkItem',
        autocompleteDataSources: {},
        assignees,
      },
      apolloProvider: mockApollo([
        [workItemByIidQuery, workItemByIidResponseHandler],
        [updateWorkItemNoteMutation, updateNoteMutationHandler],
        [updateWorkItemMutation, updateWorkItemMutationHandler],
      ]),
    });
  };

  describe('when editing', () => {
    beforeEach(() => {
      createComponent();
      findNoteActions().vm.$emit('startEditing');
      return nextTick();
    });

    it('should render a comment form', () => {
      expect(findCommentForm().exists()).toBe(true);
    });

    it('should not render note wrapper', () => {
      expect(findNoteWrapper().exists()).toBe(false);
    });

    it('updates saved draft with current note text', () => {
      expect(updateDraft).toHaveBeenCalledWith(
        `${mockWorkItemCommentNote.id}-comment`,
        mockWorkItemCommentNote.body,
      );
    });

    it('passes correct autosave key prop to comment form component', () => {
      expect(findCommentForm().props('autosaveKey')).toBe(`${mockWorkItemCommentNote.id}-comment`);
    });

    it('should hide a form and show wrapper when user cancels editing', async () => {
      findCommentForm().vm.$emit('cancelEditing');
      await nextTick();

      expect(findCommentForm().exists()).toBe(false);
      expect(findNoteWrapper().exists()).toBe(true);
    });

    it('should show the awards list when in edit mode', async () => {
      createComponent({ note: mockWorkItemCommentNote, workItemsMvc2: true });
      findNoteActions().vm.$emit('startEditing');
      await nextTick();
      expect(findAwardsList().exists()).toBe(true);
    });
  });

  describe('when submitting a form to edit a note', () => {
    it('calls update mutation with correct variables', async () => {
      createComponent();
      findNoteActions().vm.$emit('startEditing');
      await nextTick();

      findCommentForm().vm.$emit('submitForm', { commentText: updatedNoteText });

      expect(successHandler).toHaveBeenCalledWith({
        input: {
          id: mockWorkItemCommentNote.id,
          body: updatedNoteText,
        },
      });
    });

    it('hides the form after succesful mutation', async () => {
      createComponent();
      findNoteActions().vm.$emit('startEditing');
      await nextTick();

      findCommentForm().vm.$emit('submitForm', { commentText: updatedNoteText });
      await waitForPromises();

      expect(findCommentForm().exists()).toBe(false);
      expect(clearDraft).toHaveBeenCalledWith(`${mockWorkItemCommentNote.id}-comment`);
    });

    describe('when mutation fails', () => {
      beforeEach(async () => {
        createComponent({ updateNoteMutationHandler: errorHandler });
        findNoteActions().vm.$emit('startEditing');
        await nextTick();

        findCommentForm().vm.$emit('submitForm', { commentText: updatedNoteText });
        await waitForPromises();
      });

      it('opens the form again', () => {
        expect(findCommentForm().exists()).toBe(true);
      });

      it('updates the saved draft with the latest comment text', () => {
        expect(updateDraft).toHaveBeenCalledWith(
          `${mockWorkItemCommentNote.id}-comment`,
          updatedNoteText,
        );
      });

      it('emits an error', () => {
        expect(wrapper.emitted('error')).toHaveLength(1);
      });
    });
  });

  describe('when not editing', () => {
    it('should not render a comment form', () => {
      createComponent();
      expect(findCommentForm().exists()).toBe(false);
    });

    it('should render note wrapper', () => {
      createComponent();
      expect(findNoteWrapper().exists()).toBe(true);
    });

    it('renders no "edited at" information by default', () => {
      createComponent();
      expect(findEditedAt().exists()).toBe(false);
    });

    it('renders "edited at" information if the note was edited', () => {
      createComponent({
        note: {
          ...mockWorkItemCommentNote,
          lastEditedAt: '2023-02-12T07:47:40Z',
          lastEditedBy: { ...mockWorkItemCommentNote.author, webPath: 'test-path' },
        },
      });

      expect(findEditedAt().props()).toMatchObject({
        updatedAt: '2023-02-12T07:47:40Z',
        updatedByName: 'Administrator',
        updatedByPath: 'test-path',
      });
    });

    describe('main comment', () => {
      beforeEach(async () => {
        createComponent({ isFirstNote: true });
        await waitForPromises();
      });

      it('should have the note header, actions and body', () => {
        expect(findTimelineEntryItem().exists()).toBe(true);
        expect(findNoteHeader().exists()).toBe(true);
        expect(findNoteBody().exists()).toBe(true);
        expect(findNoteActions().exists()).toBe(true);
      });

      it('should have the reply button props', () => {
        expect(findNoteActions().props('showReply')).toBe(true);
      });

      it('should have the project name', () => {
        expect(findNoteActions().props('projectName')).toBe('Project name');
      });
    });

    describe('comment threads', () => {
      beforeEach(() => {
        createComponent();
      });

      it('should show avatar link with popover support', () => {
        const avatarLink = findTimelineEntryItem().findComponent(GlAvatarLink);
        const { author } = mockWorkItemCommentNote;

        expect(avatarLink.exists()).toBe(true);
        expect(avatarLink.classes()).toContain('js-user-link');
        expect(avatarLink.attributes()).toMatchObject({
          href: author.webUrl,
          'data-user-id': '1',
          'data-username': `${author.username}`,
        });
      });

      it('should have the note header, actions and body', () => {
        expect(findTimelineEntryItem().exists()).toBe(true);
        expect(findNoteHeader().exists()).toBe(true);
        expect(findNoteBody().exists()).toBe(true);
        expect(findNoteActions().exists()).toBe(true);
      });

      it('should not have the reply button props', () => {
        expect(findNoteActions().props('showReply')).toBe(false);
      });
    });

    describe('assign/unassign to commenting user', () => {
      it('calls a mutation with correct variables', async () => {
        createComponent({ assignees: mockAssignees });
        await waitForPromises();
        findNoteActions().vm.$emit('assignUser');

        await waitForPromises();

        expect(updateWorkItemMutationSuccessHandler).toHaveBeenCalledWith({
          input: {
            id: mockWorkItemId,
            assigneesWidget: {
              assigneeIds: [mockAssignees[1].id],
            },
          },
        });
      });

      it('emits an error and resets assignees if mutation was rejected', async () => {
        createComponent({
          updateWorkItemMutationHandler: errorHandler,
          assignees: [mockAssignees[0]],
        });

        await waitForPromises();

        expect(findNoteActions().props('isAuthorAnAssignee')).toEqual(true);

        findNoteActions().vm.$emit('assignUser');

        await waitForPromises();

        expect(wrapper.emitted('error')).toEqual([[i18n.updateError]]);
        expect(findNoteActions().props('isAuthorAnAssignee')).toEqual(true);
      });

      it('tracks the event', async () => {
        createComponent();
        await waitForPromises();
        const trackingSpy = mockTracking(undefined, wrapper.element, jest.spyOn);

        findNoteActions().vm.$emit('assignUser');

        await waitForPromises();

        expect(trackingSpy).toHaveBeenCalledWith(TRACKING_CATEGORY_SHOW, 'unassigned_user', {
          category: TRACKING_CATEGORY_SHOW,
          label: 'work_item_note_actions',
          property: 'type_Task',
        });
      });
    });

    describe('report abuse props', () => {
      it.each`
        currentUserId | canReportAbuse | sameAsAuthor
        ${1}          | ${false}       | ${'same as'}
        ${4}          | ${true}        | ${'not same as'}
      `(
        'should be $canReportAbuse when the author is $sameAsAuthor as the author of the note',
        ({ currentUserId, canReportAbuse }) => {
          window.gon = {
            current_user_id: currentUserId,
          };
          createComponent();

          expect(findNoteActions().props('canReportAbuse')).toBe(canReportAbuse);
        },
      );
    });

    describe('internal note', () => {
      it('does not have the internal note class set by default', () => {
        createComponent();
        expect(findTimelineEntryItem().classes()).not.toContain('internal-note');
      });

      it('timeline entry item and note header has the class for internal notes', () => {
        createComponent({
          note: {
            ...mockWorkItemCommentNote,
            internal: true,
          },
        });
        expect(findTimelineEntryItem().classes()).toContain('internal-note');
        expect(findNoteHeader().props('isInternalNote')).toBe(true);
      });
    });

    describe('author and user role badges', () => {
      describe('author badge props', () => {
        it.each`
          isWorkItemAuthor | sameAsCurrentUser | workItemByIidResponseHandler
          ${true}          | ${'same as'}      | ${workItemResponseHandler}
          ${false}         | ${'not same as'}  | ${workItemByAuthoredByDifferentUser}
        `(
          'should pass correct isWorkItemAuthor `$isWorkItemAuthor` to note actions when author is $sameAsCurrentUser as current note',
          async ({ isWorkItemAuthor, workItemByIidResponseHandler }) => {
            createComponent({ workItemByIidResponseHandler });
            await waitForPromises();

            expect(findNoteActions().props('isWorkItemAuthor')).toBe(isWorkItemAuthor);
          },
        );
      });

      describe('Max access level badge', () => {
        it('should pass the max access badge props', async () => {
          createComponent({ note: mockWorkItemCommentByMaintainer });
          await waitForPromises();

          expect(findNoteActions().props('maxAccessLevelOfAuthor')).toBe(
            mockWorkItemCommentByMaintainer.maxAccessLevelOfAuthor,
          );
        });
      });

      describe('Contributor badge', () => {
        it('should pass the contributor props', async () => {
          createComponent({ note: mockWorkItemCommentNoteByContributor });
          await waitForPromises();

          expect(findNoteActions().props('isAuthorContributor')).toBe(
            mockWorkItemCommentNoteByContributor.authorIsContributor,
          );
        });
      });
    });

    it('passes note props to awards list', () => {
      createComponent({ note: mockWorkItemCommentNote, workItemsMvc2: true });

      expect(findAwardsList().props('note')).toBe(mockWorkItemCommentNote);
      expect(findAwardsList().props('workItemIid')).toBe('1');
    });
  });
});