Automating Drag and Drop File Uploads in Selenium Using TestNG

Automating Drag and Drop File Uploads in Selenium Using TestNG

16 July 2024 Stephan Petzl Leave a comment QA

Automating file uploads via drag and drop functionality in web applications can be a challenging task. This article provides a comprehensive guide on how to achieve this using Selenium and TestNG. We will walk you through the process using practical examples and code snippets.

Introduction to Drag and Drop Automation

In many modern web applications, drag and drop functionality is used for file uploads. An example of this is the Gmail attachment feature. Automating this process requires a combination of Selenium’s WebDriver and JavaScript execution to simulate drag and drop events.

Step-by-Step Guide

1. Setting Up the Environment

Before you begin, ensure that you have the necessary tools installed:

  • Selenium WebDriver
  • TestNG
  • ChromeDriver or any other WebDriver

2. Writing the DropFile Method

The DropFile method is crucial for simulating the drag and drop event. This method injects a script that creates an input element to receive the file and then triggers the appropriate drag and drop events.

public static void DropFile(File filePath, WebElement target, int offsetX, int offsetY) {
    if (!filePath.exists())
        throw new WebDriverException("File not found: " + filePath.toString());

    WebDriver driver = ((RemoteWebElement) target).getWrappedDriver();
    JavascriptExecutor jse = (JavascriptExecutor) driver;
    WebDriverWait wait = new WebDriverWait(driver, 30);

    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));
}

3. Implementing the Test Case

Now, integrate the DropFile method into your test case. The following example demonstrates how to locate the drop area on a web page and drop a file from the local file system:

ChromeDriver driver = new ChromeDriver();
driver.get("http://html5demos.com/file-api");

// locate the drop area
WebElement droparea = driver.findElement(By.cssSelector("#holder"));

// drop the file
DropFile(new File("C:\\Downloads\\image.png"), droparea, 0, 0);

Handling Common Issues

Be aware that certain methods or classes may become deprecated over time. For instance, RemoteWebElement was deprecated in Selenium WebDriver 4.0. Always refer to the latest documentation for updates.

Conclusion

Automating drag and drop file uploads can significantly enhance your testing process, ensuring that your web application handles file uploads smoothly. This method, while technical, provides a robust solution for simulating user interactions in a test environment.

Enhancing Your Testing with Repeato

For teams looking to streamline their testing process further, consider using Repeato. Repeato is a no-code test automation tool for iOS and Android, utilizing computer vision and AI to create, run, and maintain automated tests rapidly. This tool can complement your existing Selenium setup by simplifying the creation and execution of tests, particularly for mobile applications.

For more information, check out our getting started guide or explore our comprehensive documentation.

Like this article? there’s more where that came from!