summaryrefslogtreecommitdiff
path: root/spec/javascripts/dropzone_input_spec.js
blob: 125dcdb3763f36c18855bdb9de8f99abd93b3965 (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
import $ from 'jquery';
import dropzoneInput from '~/dropzone_input';
import { TEST_HOST } from 'spec/test_constants';

const TEST_FILE = new File([], 'somefile.jpg');
TEST_FILE.upload = {};

const TEST_UPLOAD_PATH = `${TEST_HOST}/upload/file`;
const TEST_ERROR_MESSAGE = 'A big error occurred!';
const TEMPLATE = `<form class="gfm-form" data-uploads-path="${TEST_UPLOAD_PATH}">
  <textarea class="js-gfm-input"></textarea>
  <div class="uploading-error-message"></div>
</form>`;

describe('dropzone_input', () => {
  it('returns null when failed to initialize', () => {
    const dropzone = dropzoneInput($('<form class="gfm-form"></form>'));

    expect(dropzone).toBeNull();
  });

  it('returns valid dropzone when successfully initialize', () => {
    const dropzone = dropzoneInput($(TEMPLATE));

    expect(dropzone.version).toBeTruthy();
  });

  describe('shows error message', () => {
    let form;
    let dropzone;
    let xhr;
    let oldXMLHttpRequest;

    beforeEach(() => {
      form = $(TEMPLATE);

      dropzone = dropzoneInput(form);

      xhr = jasmine.createSpyObj(Object.keys(XMLHttpRequest.prototype));
      oldXMLHttpRequest = window.XMLHttpRequest;
      window.XMLHttpRequest = () => xhr;
    });

    afterEach(() => {
      window.XMLHttpRequest = oldXMLHttpRequest;
    });

    it('when AJAX fails with json', () => {
      xhr = {
        ...xhr,
        statusCode: 400,
        readyState: 4,
        responseText: JSON.stringify({ message: TEST_ERROR_MESSAGE }),
        getResponseHeader: () => 'application/json',
      };

      dropzone.processFile(TEST_FILE);

      xhr.onload();

      expect(form.find('.uploading-error-message').text()).toEqual(TEST_ERROR_MESSAGE);
    });

    it('when AJAX fails with text', () => {
      xhr = {
        ...xhr,
        statusCode: 400,
        readyState: 4,
        responseText: TEST_ERROR_MESSAGE,
        getResponseHeader: () => 'text/plain',
      };

      dropzone.processFile(TEST_FILE);

      xhr.onload();

      expect(form.find('.uploading-error-message').text()).toEqual(TEST_ERROR_MESSAGE);
    });
  });
});