Search code examples
javaseleniumselenium-webdriverwaitselenium-chromedriver

How to write wait in the method in Selenium 2?


This method of loading the page of the navigation link, it takes time to test committed. My test falls when it checks the page is loaded with the correct url. I tried to write:

waitForElementToBeDisplayed(driver.findElement(By.xpath("//a[contains(.,'"+submenus[i]+"')]")), 500);

Thread.sleep(2000);

This is my code:

public void showNavigationLinks(){
        Actions action = new Actions(driver);

        String[] submenus = {"Accessories", "iMacs", "iPads" , "iPhones" , "iPods" , "MacBook"};   

        for(int i=0;i<submenus.length;i++)
        {
            waitForElementToBeDisplayed(driver.findElement(By.xpath("//a[contains(.,'Product Category')]")), 500);
            WebElement we = driver.findElement(By.xpath("//a[contains(.,'Product Category')]"));

            action.moveToElement(we).moveToElement(driver.findElement(By.xpath("//a[contains(.,'"+submenus[i]+"')]"))).click().build().perform();

            //Checking correct URL
            waitForElementToBeDisplayed(driver.findElement(By.xpath("//a[contains(.,'"+submenus[i]+"')]")), 500);
            Assert.assertTrue("checking if URL contains: " + submenus[i],
                    driver.getCurrentUrl().toLowerCase().contains(submenus[i].toLowerCase()));
        }
}

This is my error:

java.lang.AssertionError: checking if URL contains: iMacs


Solution

  • If you know the expected URL, you can use a dynamic wait instead of a "dumb" sleep. This would wait for the URL for up to 1 minute and proceed as soon as it is found (which might be far less than 1 minute, polling twice a second):

    WebDriverWait wait = new WebDriverWait(driver, 60);
    wait.until(ExpectedConditions.urlContains(submenus[i].toLowerCase()));
    

    You could also use urlToBe (if you know the exact URL) or urlMatches (if you want to use a regex pattern).