2016-05-31 74 views
4

我想通过将文件拖动到页面中的拖放区域来测试文件上载,但是我找不到一种方法来模拟从桌面文件夹拖动文件。 我设法找到的唯一方法是以下一个 -模拟在量角器中上传文件的拖放

desktop.browser.actions().dragAndDrop(elem,target).mouseUp().perform();(Protractor) 

但是据我可以理解,它只是拖动的CSS元素。

回答

5

这是一个工作示例来模拟从桌面到拖放区域文件放置:

const dropFile = require("./drop-file.js"); 
const EC = protractor.ExpectedConditions; 

browser.ignoreSynchronization = true; 

describe('Upload tests', function() { 

    it('should drop a file to a drop area', function() { 

    browser.get('http://html5demos.com/file-api'); 

    // drop an image file on the drop area 
    dropFile($("#holder"), "./image.png"); 

    // wait for the droped image to be displayed in the drop area 
    browser.wait(EC.presenceOf($("#holder[style*='data:image']"))); 
    }); 

}); 

drop-file.js内容:

var fs = require('fs'); 
var path = require('path'); 

var JS_BIND_INPUT = function (target) { 
    var input = document.createElement('input'); 
    input.type = 'file'; 
    input.style.display = 'none'; 
    input.addEventListener('change', function() { 
    target.scrollIntoView(true); 

    var rect = target.getBoundingClientRect(), 
     x = rect.left + (rect.width >> 1), 
     y = rect.top + (rect.height >> 1), 
     data = { files: input.files }; 

    ['dragenter','dragover','drop'].forEach(function (name) { 
     var event = document.createEvent('MouseEvent'); 
     event.initMouseEvent(name, !0, !0, window, 0, 0, 0, x, y, !1, !1, !1, !1, 0, null); 
     event.dataTransfer = data; 
     target.dispatchEvent(event); 
    }); 

    document.body.removeChild(input); 
    }, false); 

    document.body.appendChild(input); 
    return input; 
}; 


/** 
* Support function to drop a file to a drop area. 
* 
* @view 
* <div id="drop-area"></div> 
* 
* @example 
* dropFile($("#drop-area"), "./image.png"); 
* 
* @param {ElementFinder} drop area 
* @param {string} file path 
*/ 
module.exports = function (dropArea, filePath) { 
    // get the full path 
    filePath = path.resolve(filePath); 

    // assert the file is present 
    fs.accessSync(filePath, fs.F_OK); 

    // resolve the drop area 
    return dropArea.getWebElement().then(function (element) { 

    // bind a new input to the drop area 
    browser.executeScript(JS_BIND_INPUT, element).then(function (input) { 

     // upload the file to the new input 
     input.sendKeys(filePath); 

    }); 
    }); 
}; 
+0

这很复杂 – SuperUberDuper

2

您不能使用量角器从桌面拖动元素,其操作仅限于浏览器功能。

你可能不得不考虑从桌面拖动到工作(除非你想测试你的操作系统),并检查一旦文件给了HTML元素,一切正常。为实现这一

的一种方式是具有以下:

dropElement.sendKeys(path); 

例如,如果该元素是,像往常一样,文件的类型的输入:

$('input[type="file"]').sendKeys(path); 

注意path应该是您要上传的文件的绝对路径,例如/Users/me/foo/bar/myFile.jsonc:\foo\bar\myFile.json

+0

你应该重新考虑你的发言。使用量角器可以将文件拖放到拖放区域。 –

+0

@FlorentB。你有一个具体的例子来支持这个陈述吗?谢谢。 – alecxe

+0

@alex,我已经做到了,但我不打算在评论中添加示例。它需要使用.executeScript在页面中注入新的元素以获取该文件。然后,在使用.sendKeys上传文件后,将放置事件与附加到放置区域的文件一起发送。 –