summaryrefslogtreecommitdiff
path: root/spec/frontend/ide/components/new_dropdown/upload_spec.js
blob: 883b365c99adec5be6c8ea3da789705928535894 (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
import { mount } from '@vue/test-utils';
import Upload from '~/ide/components/new_dropdown/upload.vue';
import waitForPromises from 'helpers/wait_for_promises';

describe('new dropdown upload', () => {
  let wrapper;

  function createComponent() {
    wrapper = mount(Upload, {
      propsData: {
        path: '',
      },
    });
  }

  const uploadFile = (file) => {
    const input = wrapper.find('input[type="file"]');
    Object.defineProperty(input.element, 'files', { value: [file] });
    input.trigger('change', file);
  };

  const waitForFileToLoad = async () => {
    await waitForPromises();
    return waitForPromises();
  };

  beforeEach(() => {
    createComponent();
  });

  describe('readFile', () => {
    beforeEach(() => {
      jest.spyOn(FileReader.prototype, 'readAsDataURL').mockImplementation(() => {});
    });

    it('calls readAsDataURL for all files', () => {
      const file = {
        type: 'images/png',
      };

      uploadFile(file);

      expect(FileReader.prototype.readAsDataURL).toHaveBeenCalledWith(file);
    });
  });

  describe('createFile', () => {
    const textFile = new File(['plain text'], 'textFile', { type: 'test/mime-text' });
    const binaryFile = new File(['😺'], 'binaryFile', { type: 'test/mime-binary' });

    beforeEach(() => {
      jest.spyOn(FileReader.prototype, 'readAsText');
    });

    it('calls readAsText and creates file in plain text (without encoding) if the file content is plain text', async () => {
      uploadFile(textFile);

      // Text file has an additional load, so need to wait twice
      await waitForFileToLoad();
      await waitForFileToLoad();

      expect(FileReader.prototype.readAsText).toHaveBeenCalledWith(textFile);
      expect(wrapper.emitted('create')[0]).toStrictEqual([
        {
          name: textFile.name,
          type: 'blob',
          content: 'plain text',
          rawPath: '',
          mimeType: 'test/mime-text',
        },
      ]);
    });

    it('creates a blob URL for the content if binary', async () => {
      uploadFile(binaryFile);

      await waitForFileToLoad();

      expect(FileReader.prototype.readAsText).not.toHaveBeenCalled();

      expect(wrapper.emitted('create')[0]).toStrictEqual([
        {
          name: binaryFile.name,
          type: 'blob',
          content: '😺', // '😺'
          rawPath: 'blob:https://gitlab.com/048c7ac1-98de-4a37-ab1b-0206d0ea7e1b',
          mimeType: 'test/mime-binary',
        },
      ]);
    });
  });
});