Search code examples
javaseleniumselenium-webdrivertestngcucumber-java

clicking the download button is not working properly in selenium java


I did not face any error as no element found however my test case is passed in console but when i checked in download folder it shows some temp file instead of actual image file. It will be very useful if someone solve this issue.

driver.get("https://demoqa.com/elements");

driver.manage().window().maximize();

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            
            // Here normal 'findElement' is not working, hence used the javascript executor
            
            WebElement leftmenu = driver.findElement(By.xpath("(//li[@id='item-7']//span)[1]"));
            JavascriptExecutor executor = (JavascriptExecutor)driver;
            executor.executeScript("arguments[0].click();", leftmenu);  //clicking the left menu 
            
            Thread.sleep(5000);
            
            driver.findElement(By.xpath("//a[@download='sampleFile.jpeg']")).click();  // download button

Solution

  • You are finishing the test run and closing the browser immediately after clicking the download button.
    Try adding a simple sleep after clicking it.
    Also, you should not use hardcoded pauses like this

    Thread.sleep(5000);
    

    Explicit wait should be used instead.
    Also please try to wait until the element is visible, as I wrote here. I think this will let you clicking it with regular driver .click() method.
    Try this:

    driver.get("https://demoqa.com/elements");
    
    driver.manage().window().maximize();
    WebDriverWait wait = new WebDriverWait(driver, globalDelay);
                
    // Here normal 'findElement' is not working, hence used the javascript executor
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(//li[@id='item-7']//span)[1]"))).click();            
    //WebElement leftmenu = driver.findElement(By.xpath("(//li[@id='item-7']//span)[1]"));
    //JavascriptExecutor executor = (JavascriptExecutor)driver;
    //executor.executeScript("arguments[0].click();", leftmenu);  //clicking the left menu 
    
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[@download='sampleFile.jpeg']"))).click();            
    
    Thread.sleep(5000);