Dave Wright Music

Watir Webdriver, Dropzone.js, upload image

I spent several days stuck on this issue and couldn’t find any direct results online. (Although I did find some selenium related examples which did help)

Say you are testing a user profile image upload feature. The site uses dropzone.js which a great drag and drop library. Since there is not form file upload field, it can be challenging to test.

    require "watir-webdriver"
    @@profile_image = '/home/user/some_image.jpg'
    @b = Watir::Browser.new :firefox
    @b.a(:id, 'user_profile').when_present.click
    @b.button(:id, 'edit_user_image').when_present.click
    @b.div(:id, 'dropzone').wait_until_present
    @b.div(:id, 'dropzone').visible?
    # magic part #1
    @b.execute_script("
        upl_prof_img = $('#upl_prof_img'); 
        if (upl_prof_img.length === 0) {
          upl_prof_img = window.$('<input/>').attr({id: 'upl_prof_img', type:'file'}).appendTo('.dropzone');
        }
        return upl_prof_img; // return is crucial!
    ")
    
    @b.file_field(:id, 'upl_prof_img').wait_until_present
    # set file to upload to the input file added to DOM
    @b.file_field(:id, 'upl_prof_img').set(@@profile_image)
    
    # magic part #2
    @b.execute_script("
      var e = jQuery.Event('drop', { 
          dataTransfer : { files : [upl_prof_img.files[0]]}
      });
      $('.dropzone')[0].dropzone.listeners[0].events.drop(e);
    ")

Anyway that worked for me, hopefully it will lead you forward.

(kudos:
http://stackoverflow.com/questions/32880524/how-do-you-test-uploading-a-file-with-capybara-and-dropzone/32880525#32880525
http://blog.paulrugelhiatt.com/rails/testing/capybara/dropzonejs/2014/12/29/test-dropzonejs-file-uploads-with-capybara.html

Leave a Reply