Automating html/jaggery File Uploader with Selenium

When writing automated UI tests for web-apps using Selenium, suppose there is a requirement to trigger a file upload function, where a user brows for a file in the file system, select a file, and then uploads it. Typically the simple html snippet would look as follows.

            <form id="fileUploadForm" class="row">
                <div> Data Source: 
                    <input type="text" id="datasetName" name="datasetName" disabled/>
                    <input type="button" id="datasetOpen" value="Browse" />
                </div> 
                <input type="file" name="dataFile" id="dataFile">
                <input type="submit" value="Import">
            </form>

What happens inside the html is, when a user selects a file, it's path is written to the <input type="file">, and once the submit/upload is clicked, the file gets uploaded.
The complication of triggering this by Selenium is that, once the 'browse' button is clicked, the popup opens is a OS level window, thus selenium driver cannot handle it. A workaround would be to set the file path to the <input type ='file' name='dataFile'> html element, rather than browsing the file. But again, Selenium driver is unable to set the path to this element as it is an 'hidden' element by default.

Therefore as a workaround, it is possible to change the hidden attribute of the html file input element through JavaScript and then set the file path using Selenium driver, in the following way.

            WebElement fileElement = driver.findElement(By.id("dataFile"));
            // enable the visibility of the file input element
            ((JavascriptExecutor)driver).executeScript("arguments[0].style.visibility = 'visible';" +
                    "arguments[0].style.height = '1px'; arguments[0].style.width = '1px'; arguments[0]" +
                    ".style.opacity = 1", fileElement);
           fileElement.sendKeys("path/to/the/file");

Even though altering the original application through tests is discouraged, it is acceptable to do so in situations like above where there are no other solutions available, and to provide an automate friendly UI, without altering the functionality. 

Share:

1 comments