Selenium: Drag and Drop from file system to WebDriver?

后端 未结 4 1579
野的像风
野的像风 2020-12-01 10:56

I have to test a web-application which contains a drag and drop area for uploading files from the local file system. My test environment is based on C#.

For the auto

4条回答
  •  被撕碎了的回忆
    2020-12-01 11:42

    If you're using Selenide:

        public static void dragAndDropFileUpload(File file, SelenideElement target) throws IOException {
    
        String inputId = "seleniumDragAndDropInput";
    
        // Create the FileList
        executeJavaScript(inputId + "_files = [];");
            executeJavaScript(inputId + "_files.push(new File([new Blob(['" + file.getAbsolutePath() + "'], {type: '" + Files.probeContentType(file.toPath()) + "'})], '" + file.getName() + "'));");
    
    
        String targetId = target.getAttribute("id");
    
        // Add an id if the target doesn't have one
        if (targetId == null || targetId.isEmpty()) {
            targetId = "seleniumDragAndDropInput_target";
            executeJavaScript("sId=function(e, i){e.id = i;};sId(arguments[0], arguments[1]);", target, targetId);
        }
    
        // Add the item function the the FileList
        // Create the drop event and dispatch it on the target
        String initEventJS = inputId + "_files.item = function (i) {return this[i];};"
                + "var eve=document.createEvent(\"HTMLEvents\");"
                + "eve.initEvent(\"drop\", true, true);"
                + "eve.dataTransfer = {files:seleniumDragAndDropInput_files};"
                + "eve.preventDefault = function () {};"
                + "eve.type = \"drop\";"
                + "document.getElementById('" + targetId + "').dispatchEvent(eve);";
    
        executeJavaScript(initEventJS);
    
        if (targetId == "seleniumDragAndDropInput_target") {
            executeJavaScript("document.getElementById('seleniumDragAndDropInput_target').id = null");
        }
    }
    

提交回复
热议问题