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
        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
      var e = jQuery.Event('drop', { 
          dataTransfer : { files : [upl_prof_img.files[0]]}

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


Leave a Reply