summaryrefslogtreecommitdiff
path: root/spec/frontend/lib/utils/file_upload_spec.js
blob: 1dff5d4f925dd26df970ca645948ed5aef728864 (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
import fileUpload, { getFilename } from '~/lib/utils/file_upload';

describe('File upload', () => {
  beforeEach(() => {
    setFixtures(`
      <form>
        <button class="js-button" type="button">Click me!</button>
        <input type="text" class="js-input" />
        <span class="js-filename"></span>
      </form>
    `);
  });

  describe('when there is a matching button and input', () => {
    beforeEach(() => {
      fileUpload('.js-button', '.js-input');
    });

    it('clicks file input after clicking button', () => {
      const btn = document.querySelector('.js-button');
      const input = document.querySelector('.js-input');

      jest.spyOn(input, 'click').mockReturnValue();

      btn.click();

      expect(input.click).toHaveBeenCalled();
    });

    it('updates file name text', () => {
      const input = document.querySelector('.js-input');

      input.value = 'path/to/file/index.js';

      input.dispatchEvent(new CustomEvent('change'));

      expect(document.querySelector('.js-filename').textContent).toEqual('index.js');
    });
  });

  it('fails gracefully when there is no matching button', () => {
    const input = document.querySelector('.js-input');
    const btn = document.querySelector('.js-button');
    fileUpload('.js-not-button', '.js-input');

    jest.spyOn(input, 'click').mockReturnValue();

    btn.click();

    expect(input.click).not.toHaveBeenCalled();
  });

  it('fails gracefully when there is no matching input', () => {
    const input = document.querySelector('.js-input');
    const btn = document.querySelector('.js-button');
    fileUpload('.js-button', '.js-not-input');

    jest.spyOn(input, 'click').mockReturnValue();

    btn.click();

    expect(input.click).not.toHaveBeenCalled();
  });
});

describe('getFilename', () => {
  it('returns first value correctly', () => {
    const event = {
      clipboardData: {
        getData: () => 'test.png\rtest.txt',
      },
    };

    expect(getFilename(event)).toBe('test.png');
  });
});