Below is a custom function in which we pass the xpath of the element we want to click as xpathExpTarget ,the element we want to look for on next page as xpathExpWait and number of times we want to run the for loop as maxTime.Once xpathExpTarget is clicked we check if xpathExpWait is present and whether that element is displayed. We can run this test for maximum of times based on maxTime argument we passed into our function using a for loop. Using for loop we click for first time and if the webelement will be present and displayed and so if statement will come true then return will be executed and we come out of while loop else wait function will be called and code waits for the number of secs passed in wait function and then for loop runs for second time and so on.
If for loop runs for max times and click never works and that means webelement is never found and we use Assert statement to fail the test.
public void clickAndWait(String xpathExpTarget , String xpathExpWait ,int maxTime){
for(int i=1;i<=maxTime;i++){
System.out.println("Running for iteration " + i);
driver.findElement(By.xpath(xpathExpTarget)).click();
// check presence of other ele
if(isElementPresent(xpathExpWait) && driver.findElement(By.xpath(xpathExpWait)).isDisplayed()){
// if present - success.. return
return;
}else{
// else wait for 1 sec
wait(1);
}
}
Assert.fail("Target element coming after clicking on "+xpathExpTarget );
}
isElementPresent and wait functions definations are below.
public boolean isElementPresent(String xpathExp){
int numberOfElements = driver.findElements(By.xpath(xpathExp)).size();
if(numberOfElements==0)
return false;
else
return true;
}
public void wait(int time){
try {
Thread.sleep(time*1000);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}