summaryrefslogtreecommitdiff
path: root/spec/frontend/content_editor/extensions/attachment_spec.js
blob: 6b804b3b4c688990756805d8b5ad8f4060cace3e (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
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import waitForPromises from 'helpers/wait_for_promises';
import Attachment from '~/content_editor/extensions/attachment';
import Image from '~/content_editor/extensions/image';
import Audio from '~/content_editor/extensions/audio';
import Video from '~/content_editor/extensions/video';
import Link from '~/content_editor/extensions/link';
import Loading from '~/content_editor/extensions/loading';
import { VARIANT_DANGER } from '~/flash';
import { HTTP_STATUS_INTERNAL_SERVER_ERROR, HTTP_STATUS_OK } from '~/lib/utils/http_status';
import eventHubFactory from '~/helpers/event_hub_factory';
import { createTestEditor, createDocBuilder } from '../test_utils';
import {
  PROJECT_WIKI_ATTACHMENT_IMAGE_HTML,
  PROJECT_WIKI_ATTACHMENT_AUDIO_HTML,
  PROJECT_WIKI_ATTACHMENT_VIDEO_HTML,
  PROJECT_WIKI_ATTACHMENT_LINK_HTML,
} from '../test_constants';

describe('content_editor/extensions/attachment', () => {
  let tiptapEditor;
  let doc;
  let p;
  let image;
  let audio;
  let video;
  let loading;
  let link;
  let renderMarkdown;
  let mock;
  let eventHub;

  const uploadsPath = '/uploads/';
  const imageFile = new File(['foo'], 'test-file.png', { type: 'image/png' });
  const audioFile = new File(['foo'], 'test-file.mp3', { type: 'audio/mpeg' });
  const videoFile = new File(['foo'], 'test-file.mp4', { type: 'video/mp4' });
  const attachmentFile = new File(['foo'], 'test-file.zip', { type: 'application/zip' });

  const expectDocumentAfterTransaction = ({ number, expectedDoc, action }) => {
    return new Promise((resolve) => {
      let counter = 1;
      const handleTransaction = async () => {
        if (counter === number) {
          expect(tiptapEditor.state.doc.toJSON()).toEqual(expectedDoc.toJSON());
          tiptapEditor.off('update', handleTransaction);
          await waitForPromises();
          resolve();
        }

        counter += 1;
      };

      tiptapEditor.on('update', handleTransaction);
      action();
    });
  };

  beforeEach(() => {
    renderMarkdown = jest.fn();
    eventHub = eventHubFactory();

    tiptapEditor = createTestEditor({
      extensions: [
        Loading,
        Link,
        Image,
        Audio,
        Video,
        Attachment.configure({ renderMarkdown, uploadsPath, eventHub }),
      ],
    });

    ({
      builders: { doc, p, image, audio, video, loading, link },
    } = createDocBuilder({
      tiptapEditor,
      names: {
        loading: { markType: Loading.name },
        image: { nodeType: Image.name },
        link: { nodeType: Link.name },
        audio: { nodeType: Audio.name },
        video: { nodeType: Video.name },
      },
    }));

    mock = new MockAdapter(axios);
  });

  afterEach(() => {
    mock.reset();
  });

  it.each`
    eventType  | propName         | eventData                                                             | output
    ${'paste'} | ${'handlePaste'} | ${{ clipboardData: { getData: jest.fn(), files: [attachmentFile] } }} | ${true}
    ${'paste'} | ${'handlePaste'} | ${{ clipboardData: { getData: jest.fn(), files: [] } }}               | ${undefined}
    ${'drop'}  | ${'handleDrop'}  | ${{ dataTransfer: { getData: jest.fn(), files: [attachmentFile] } }}  | ${true}
  `('handles $eventType properly', ({ eventType, propName, eventData, output }) => {
    const event = Object.assign(new Event(eventType), eventData);
    const handled = tiptapEditor.view.someProp(propName, (eventHandler) => {
      return eventHandler(tiptapEditor.view, event);
    });

    expect(handled).toBe(output);
  });

  describe('uploadAttachment command', () => {
    let initialDoc;
    beforeEach(() => {
      initialDoc = doc(p(''));
      tiptapEditor.commands.setContent(initialDoc.toJSON());
    });

    describe.each`
      nodeType   | mimeType        | html                                  | file         | mediaType
      ${'image'} | ${'image/png'}  | ${PROJECT_WIKI_ATTACHMENT_IMAGE_HTML} | ${imageFile} | ${(attrs) => image(attrs)}
      ${'audio'} | ${'audio/mpeg'} | ${PROJECT_WIKI_ATTACHMENT_AUDIO_HTML} | ${audioFile} | ${(attrs) => audio(attrs)}
      ${'video'} | ${'video/mp4'}  | ${PROJECT_WIKI_ATTACHMENT_VIDEO_HTML} | ${videoFile} | ${(attrs) => video(attrs)}
    `('when the file has $nodeType mime type', ({ mimeType, html, file, mediaType }) => {
      const base64EncodedFile = `data:${mimeType};base64,Zm9v`;

      beforeEach(() => {
        renderMarkdown.mockResolvedValue(html);
      });

      describe('when uploading succeeds', () => {
        const successResponse = {
          link: {
            markdown: `![test-file](${file.name})`,
          },
        };

        beforeEach(() => {
          mock.onPost().reply(HTTP_STATUS_OK, successResponse);
        });

        it('inserts a media content with src set to the encoded content and uploading true', async () => {
          const expectedDoc = doc(p(mediaType({ uploading: true, src: base64EncodedFile })));

          await expectDocumentAfterTransaction({
            number: 1,
            expectedDoc,
            action: () => tiptapEditor.commands.uploadAttachment({ file }),
          });
        });

        it('updates the inserted content with canonicalSrc when upload is successful', async () => {
          const expectedDoc = doc(
            p(
              mediaType({
                canonicalSrc: file.name,
                src: base64EncodedFile,
                alt: 'test-file',
                uploading: false,
              }),
            ),
          );

          await expectDocumentAfterTransaction({
            number: 2,
            expectedDoc,
            action: () => tiptapEditor.commands.uploadAttachment({ file }),
          });
        });
      });

      describe('when uploading request fails', () => {
        beforeEach(() => {
          mock.onPost().reply(HTTP_STATUS_INTERNAL_SERVER_ERROR);
        });

        it('resets the doc to original state', async () => {
          const expectedDoc = doc(p(''));

          await expectDocumentAfterTransaction({
            number: 2,
            expectedDoc,
            action: () => tiptapEditor.commands.uploadAttachment({ file }),
          });
        });

        it('emits an alert event that includes an error message', () => {
          tiptapEditor.commands.uploadAttachment({ file });

          return new Promise((resolve) => {
            eventHub.$on('alert', ({ message, variant }) => {
              expect(variant).toBe(VARIANT_DANGER);
              expect(message).toBe('An error occurred while uploading the file. Please try again.');
              resolve();
            });
          });
        });
      });
    });

    describe('when the file has a zip (or any other attachment) mime type', () => {
      const markdownApiResult = PROJECT_WIKI_ATTACHMENT_LINK_HTML;

      beforeEach(() => {
        renderMarkdown.mockResolvedValue(markdownApiResult);
      });

      describe('when uploading succeeds', () => {
        const successResponse = {
          link: {
            markdown: '[test-file](test-file.zip)',
          },
        };

        beforeEach(() => {
          mock.onPost().reply(HTTP_STATUS_OK, successResponse);
        });

        it('inserts a loading mark', async () => {
          const expectedDoc = doc(p(loading({ label: 'test-file' })));

          await expectDocumentAfterTransaction({
            number: 1,
            expectedDoc,
            action: () => tiptapEditor.commands.uploadAttachment({ file: attachmentFile }),
          });
        });

        it('updates the loading mark with a link with canonicalSrc and href attrs', async () => {
          const [, group, project] = markdownApiResult.match(/\/(group[0-9]+)\/(project[0-9]+)\//);
          const expectedDoc = doc(
            p(
              link(
                {
                  canonicalSrc: 'test-file.zip',
                  href: `/${group}/${project}/-/wikis/test-file.zip`,
                },
                'test-file',
              ),
            ),
          );

          await expectDocumentAfterTransaction({
            number: 2,
            expectedDoc,
            action: () => tiptapEditor.commands.uploadAttachment({ file: attachmentFile }),
          });
        });
      });

      describe('when uploading request fails', () => {
        beforeEach(() => {
          mock.onPost().reply(HTTP_STATUS_INTERNAL_SERVER_ERROR);
        });

        it('resets the doc to orginal state', async () => {
          const expectedDoc = doc(p(''));

          await expectDocumentAfterTransaction({
            number: 2,
            expectedDoc,
            action: () => tiptapEditor.commands.uploadAttachment({ file: attachmentFile }),
          });
        });

        it('emits an alert event that includes an error message', () => {
          tiptapEditor.commands.uploadAttachment({ file: attachmentFile });

          eventHub.$on('alert', ({ message, variant }) => {
            expect(variant).toBe(VARIANT_DANGER);
            expect(message).toBe('An error occurred while uploading the file. Please try again.');
          });
        });
      });
    });
  });
});