BigW Consortium Gitlab

dropzone_helper.rb 2.63 KB
Newer Older
1 2 3 4 5 6 7 8
module DropzoneHelper
  # Provides a way to perform `attach_file` for a Dropzone-based file input
  #
  # This is accomplished by creating a standard HTML file input on the page,
  # performing `attach_file` on that field, and then triggering the appropriate
  # Dropzone events to perform the actual upload.
  #
  # This method waits for the upload to complete before returning.
9 10 11 12 13 14
  # max_file_size is an optional parameter.
  # If it's not 0, then it used in dropzone.maxFilesize parameter.
  # wait_for_queuecomplete is an optional parameter.
  # If it's 'false', then the helper will NOT wait for backend response
  # It lets to test behaviors while AJAX is processing.
  def dropzone_file(files, max_file_size = 0, wait_for_queuecomplete = true)
15 16
    # Generate a fake file input that Capybara can attach to
    page.execute_script <<-JS.strip_heredoc
17
      $('#fakeFileInput').remove();
18
      var fakeFileInput = window.$('<input/>').attr(
19
        {id: 'fakeFileInput', type: 'file', multiple: true}
20 21 22 23 24
      ).appendTo('body');

      window._dropzoneComplete = false;
    JS

25 26
    # Attach files to the fake input selector with Capybara
    attach_file('fakeFileInput', files)
27 28 29 30

    # Manually trigger a Dropzone "drop" event with the fake input's file list
    page.execute_script <<-JS.strip_heredoc
      var dropzone = $('.div-dropzone')[0].dropzone;
31 32 33 34 35 36
      dropzone.options.autoProcessQueue = false;

      if (#{max_file_size} > 0) {
        dropzone.options.maxFilesize = #{max_file_size};
      }

37 38 39
      dropzone.on('queuecomplete', function() {
        window._dropzoneComplete = true;
      });
40 41 42 43 44 45 46 47 48 49

      var fileList = [$('#fakeFileInput')[0].files];

      $.map(fileList, function(file){
        var e = jQuery.Event('drop', { dataTransfer : { files : file } });

        dropzone.listeners[0].events.drop(e);
      });

      dropzone.processQueue();
50 51
    JS

52 53 54 55
    if wait_for_queuecomplete
      # Wait until Dropzone's fired `queuecomplete`
      loop until page.evaluate_script('window._dropzoneComplete === true')
    end
56
  end
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75

  def drop_in_dropzone(file_path)
    # Generate a fake input selector
    page.execute_script <<-JS
      var fakeFileInput = window.$('<input/>').attr(
        {id: 'fakeFileInput', type: 'file'}
      ).appendTo('body');
    JS

    # Attach the file to the fake input selector with Capybara
    attach_file('fakeFileInput', file_path)

    # Add the file to a fileList array and trigger the fake drop event
    page.execute_script <<-JS
      var fileList = [$('#fakeFileInput')[0].files[0]];
      var e = jQuery.Event('drop', { dataTransfer : { files : fileList } });
      $('.dropzone')[0].dropzone.listeners[0].events.drop(e);
    JS
  end
76
end