Selenium: Drag and Drop from file system to WebDriver?

后端 未结 4 1567
野的像风
野的像风 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:27

    You can do this with JSExecutor:

    public void dropFile(File filePath, WebElement target, int offsetX, int offsetY) {
            if (!filePath.exists())
                throw new WebDriverException("File not found: " + filePath.toString());
    
            JavascriptExecutor jse = (JavascriptExecutor) driver;
    
            String JS_DROP_FILE =
                    "var target = arguments[0]," +
                            "    offsetX = arguments[1]," +
                            "    offsetY = arguments[2]," +
                            "    document = target.ownerDocument || document," +
                            "    window = document.defaultView || window;" +
                            "" +
                            "var input = document.createElement('INPUT');" +
                            "input.type = 'file';" +
                            "input.style.display = 'none';" +
                            "input.onchange = function () {" +
                            "  var rect = target.getBoundingClientRect()," +
                            "      x = rect.left + (offsetX || (rect.width >> 1))," +
                            "      y = rect.top + (offsetY || (rect.height >> 1))," +
                            "      dataTransfer = { files: this.files };" +
                            "" +
                            "  ['dragenter', 'dragover', 'drop'].forEach(function (name) {" +
                            "    var evt = document.createEvent('MouseEvent');" +
                            "    evt.initMouseEvent(name, !0, !0, window, 0, 0, 0, x, y, !1, !1, !1, !1, 0, null);" +
                            "    evt.dataTransfer = dataTransfer;" +
                            "    target.dispatchEvent(evt);" +
                            "  });" +
                            "" +
                            "  setTimeout(function () { document.body.removeChild(input); }, 25);" +
                            "};" +
                            "document.body.appendChild(input);" +
                            "return input;";
    
            WebElement input = (WebElement) jse.executeScript(JS_DROP_FILE, target, offsetX, offsetY);
            input.sendKeys(filePath.getAbsoluteFile().toString());
            wait.until(ExpectedConditions.stalenessOf(input));
        }
    

提交回复
热议问题