Automating Drag and Drop File Uploads with Selenium and TestNG

Automating Drag and Drop File Uploads with Selenium and TestNG

3 July 2024 Stephan Petzl Leave a comment QA

Automating file uploads via drag and drop in web applications can be challenging, particularly when dealing with external files. In this article, we will explore how to achieve this using Selenium and TestNG, with a focus on practical examples and step-by-step guidance.

Overview of the Problem

Users often need to upload files to web applications by dragging and dropping them into specific areas. A common example is attaching files in Gmail. Automating this process ensures efficiency and accuracy in testing. Below, we provide a detailed approach to automating drag and drop file uploads using Selenium.

Step-by-Step Solution

To automate the drag and drop file upload, you can use a script injection method in Selenium. This method involves creating an <input> element to receive the file and simulating the drag and drop events. Here’s a practical example:

Example Code

The following code demonstrates how to drop an image file from the file system onto a drop area on a web page:

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

DropFile Method

The DropFile method creates an <input> element and simulates the 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));
      }
    
  

Common Issues and Solutions

While the above method is effective, some users have encountered issues with deprecated classes in newer versions of Selenium. If you face such issues, consider using updated methods or alternative approaches, such as leveraging third-party tools like AutoIT for handling file uploads.

Conclusion

Automating drag and drop file uploads in Selenium can significantly enhance your testing efficiency and accuracy. By following the steps outlined above, you can implement a robust solution for your web applications.

For those looking to streamline their testing processes further, consider using tools like Repeato. Repeato is a no-code test automation tool for iOS and Android that simplifies the creation, execution, and maintenance of automated tests. Its AI and computer vision capabilities make it particularly fast and efficient, ensuring high-quality assurance with minimal setup and usage complexity.

Explore more about automated testing and related topics in our blog.

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