summaryrefslogtreecommitdiff
path: root/spec/frontend/vue_shared/components/markdown/field_spec.js
blob: d1c4d777d447d466f98f042f563b32dfaf6d600b (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
import { nextTick } from 'vue';
import AxiosMockAdapter from 'axios-mock-adapter';
import $ from 'jquery';
import { TEST_HOST, FIXTURES_PATH } from 'spec/test_constants';
import axios from '~/lib/utils/axios_utils';
import MarkdownField from '~/vue_shared/components/markdown/field.vue';
import MarkdownFieldHeader from '~/vue_shared/components/markdown/header.vue';
import { mountExtended } from 'helpers/vue_test_utils_helper';

const markdownPreviewPath = `${TEST_HOST}/preview`;
const markdownDocsPath = `${TEST_HOST}/docs`;
const textareaValue = 'testing\n123';
const uploadsPath = 'test/uploads';

function assertMarkdownTabs(isWrite, writeLink, previewLink, wrapper) {
  expect(writeLink.element.children[0].classList.contains('active')).toBe(isWrite);
  expect(previewLink.element.children[0].classList.contains('active')).toBe(!isWrite);
  expect(wrapper.find('.md-preview-holder').element.style.display).toBe(isWrite ? 'none' : '');
}

describe('Markdown field component', () => {
  let axiosMock;
  let subject;

  beforeEach(() => {
    axiosMock = new AxiosMockAdapter(axios);
    // window.uploads_path is needed for dropzone to initialize
    window.uploads_path = uploadsPath;
  });

  afterEach(() => {
    subject.destroy();
    axiosMock.restore();
  });

  function createSubject({ lines = [], enablePreview = true } = {}) {
    // We actually mount a wrapper component so that we can force Vue to rerender classes in order to test a regression
    // caused by mixing Vanilla JS and Vue.
    subject = mountExtended(
      {
        components: {
          MarkdownField,
        },
        props: {
          wrapperClasses: {
            type: String,
            required: false,
            default: '',
          },
        },
        template: `
<markdown-field :class="wrapperClasses" v-bind="$attrs">
  <template #textarea>
    <textarea class="js-gfm-input" :value="$attrs.textareaValue"></textarea>
  </template>
</markdown-field>`,
      },
      {
        propsData: {
          markdownDocsPath,
          markdownPreviewPath,
          isSubmitting: false,
          textareaValue,
          lines,
          enablePreview,
        },
        provide: {
          glFeatures: {
            contactsAutocomplete: true,
          },
        },
      },
    );
  }

  const getPreviewLink = () => subject.findByTestId('preview-tab');
  const getWriteLink = () => subject.findByTestId('write-tab');
  const getMarkdownButton = () => subject.find('.js-md');
  const getListBulletedButton = () => subject.findAll('.js-md[title="Add a bullet list"]');
  const getVideo = () => subject.find('video');
  const getAttachButton = () => subject.find('.button-attach-file');
  const clickAttachButton = () => getAttachButton().trigger('click');
  const findDropzone = () => subject.find('.div-dropzone');

  describe('mounted', () => {
    const previewHTML = `
    <p>markdown preview</p>
    <video src="${FIXTURES_PATH}/static/mock-video.mp4"></video>
  `;
    let previewLink;
    let writeLink;
    let dropzoneSpy;

    beforeEach(() => {
      dropzoneSpy = jest.fn();
      createSubject();
      findDropzone().element.addEventListener('click', dropzoneSpy);
    });

    it('renders textarea inside backdrop', () => {
      expect(subject.find('.zen-backdrop textarea').element).not.toBeNull();
    });

    it('renders referenced commands on markdown preview', async () => {
      axiosMock
        .onPost(markdownPreviewPath)
        .reply(200, { references: { users: [], commands: 'test command' } });

      previewLink = getPreviewLink();
      previewLink.vm.$emit('click', { target: {} });

      await axios.waitFor(markdownPreviewPath);
      const referencedCommands = subject.find('[data-testid="referenced-commands"]');

      expect(referencedCommands.exists()).toBe(true);
      expect(referencedCommands.text()).toContain('test command');
    });

    describe('markdown preview', () => {
      beforeEach(() => {
        axiosMock.onPost(markdownPreviewPath).reply(200, { body: previewHTML });
      });

      it('sets preview link as active', async () => {
        previewLink = getPreviewLink();
        previewLink.vm.$emit('click', { target: {} });

        await nextTick();
        expect(previewLink.element.children[0].classList.contains('active')).toBe(true);
      });

      it('shows preview loading text', async () => {
        previewLink = getPreviewLink();
        previewLink.vm.$emit('click', { target: {} });

        await nextTick();
        expect(subject.find('.md-preview-holder').element.textContent.trim()).toContain('Loading…');
      });

      it('renders markdown preview and GFM', async () => {
        const renderGFMSpy = jest.spyOn($.fn, 'renderGFM');

        previewLink = getPreviewLink();

        previewLink.vm.$emit('click', { target: {} });

        await axios.waitFor(markdownPreviewPath);
        expect(subject.find('.md-preview-holder').element.innerHTML).toContain(previewHTML);
        expect(renderGFMSpy).toHaveBeenCalled();
      });

      it('calls video.pause() on comment input when isSubmitting is changed to true', async () => {
        previewLink = getPreviewLink();
        previewLink.vm.$emit('click', { target: {} });

        await axios.waitFor(markdownPreviewPath);
        const video = getVideo();
        const callPause = jest.spyOn(video.element, 'pause').mockImplementation(() => true);

        subject.setProps({ isSubmitting: true });

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

      it('clicking already active write or preview link does nothing', async () => {
        writeLink = getWriteLink();
        previewLink = getPreviewLink();

        writeLink.vm.$emit('click', { target: {} });
        await nextTick();

        assertMarkdownTabs(true, writeLink, previewLink, subject);
        writeLink.vm.$emit('click', { target: {} });
        await nextTick();

        assertMarkdownTabs(true, writeLink, previewLink, subject);
        previewLink.vm.$emit('click', { target: {} });
        await nextTick();

        assertMarkdownTabs(false, writeLink, previewLink, subject);
        previewLink.vm.$emit('click', { target: {} });
        await nextTick();

        assertMarkdownTabs(false, writeLink, previewLink, subject);
      });
    });

    describe('markdown buttons', () => {
      it('converts single words', async () => {
        const textarea = subject.find('textarea').element;
        textarea.setSelectionRange(0, 7);
        const markdownButton = getMarkdownButton();
        markdownButton.trigger('click');

        await nextTick();
        expect(textarea.value).toContain('**testing**');
      });

      it('converts a line', async () => {
        const textarea = subject.find('textarea').element;
        textarea.setSelectionRange(0, 0);
        const markdownButton = getListBulletedButton();
        markdownButton.trigger('click');

        await nextTick();
        expect(textarea.value).toContain('- testing');
      });

      it('converts multiple lines', async () => {
        const textarea = subject.find('textarea').element;
        textarea.setSelectionRange(0, 50);
        const markdownButton = getListBulletedButton();
        markdownButton.trigger('click');

        await nextTick();
        expect(textarea.value).toContain('- testing\n- 123');
      });
    });

    it('should render attach a file button', () => {
      expect(getAttachButton().text()).toBe('Attach a file');
    });

    it('should trigger dropzone when attach button is clicked', () => {
      expect(dropzoneSpy).not.toHaveBeenCalled();

      clickAttachButton();

      expect(dropzoneSpy).toHaveBeenCalled();
    });

    describe('when textarea has changed', () => {
      beforeEach(async () => {
        // Do something to trigger rerendering the class
        subject.setProps({ wrapperClasses: 'foo' });

        await nextTick();
      });

      it('should have rerendered classes and kept gfm-form', () => {
        expect(subject.classes()).toEqual(expect.arrayContaining(['gfm-form', 'foo']));
      });

      it('should trigger dropzone when attach button is clicked', () => {
        expect(dropzoneSpy).not.toHaveBeenCalled();

        clickAttachButton();

        expect(dropzoneSpy).toHaveBeenCalled();
      });

      describe('mentioning all users', () => {
        const users = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].map((i) => `user_${i}`);

        it('shows warning on mention of all users', async () => {
          axiosMock.onPost(markdownPreviewPath).reply(200, { references: { users } });

          subject.setProps({ textareaValue: 'hello @all' });

          await axios.waitFor(markdownPreviewPath).then(() => {
            expect(subject.text()).toContain(
              'You are about to add 11 people to the discussion. They will all receive a notification.',
            );
          });
        });

        it('removes warning when all mention is removed', async () => {
          axiosMock.onPost(markdownPreviewPath).reply(200, { references: { users } });

          subject.setProps({ textareaValue: 'hello @all' });

          await axios.waitFor(markdownPreviewPath);

          jest.spyOn(axios, 'post');

          subject.setProps({ textareaValue: 'hello @allan' });

          await nextTick();

          expect(axios.post).not.toHaveBeenCalled();
          expect(subject.text()).not.toContain(
            'You are about to add 11 people to the discussion. They will all receive a notification.',
          );
        });

        it('removes warning when all mention is removed while endpoint is loading', async () => {
          axiosMock.onPost(markdownPreviewPath).reply(200, { references: { users } });
          jest.spyOn(axios, 'post');

          subject.setProps({ textareaValue: 'hello @all' });

          await nextTick();

          subject.setProps({ textareaValue: 'hello @allan' });

          await axios.waitFor(markdownPreviewPath);

          expect(axios.post).toHaveBeenCalled();
          expect(subject.text()).not.toContain(
            'You are about to add 11 people to the discussion. They will all receive a notification.',
          );
        });
      });
    });
  });

  describe('suggestions', () => {
    it('escapes new line characters', () => {
      createSubject({ lines: [{ rich_text: 'hello world\\n' }] });

      expect(subject.find('[data-testid="markdownHeader"]').props('lineContent')).toBe(
        'hello world%br',
      );
    });
  });

  it('allows enabling and disabling Markdown Preview', () => {
    createSubject({ enablePreview: false });

    expect(subject.findComponent(MarkdownFieldHeader).props('enablePreview')).toBe(false);

    subject.destroy();
    createSubject({ enablePreview: true });

    expect(subject.findComponent(MarkdownFieldHeader).props('enablePreview')).toBe(true);
  });
});