Reputation: 219
I have a scenario where I am not able to proceed further:
I have two buttons on the page (both the buttons are in the same frame). I'm using an Iterator
for the Button 1
. When we click the Button 1
, it makes an AJAX call. I see a mouse loading animation for a second and then the product is added to the cart.
Say, if I have 5 buttons of the same type & want to click all the 5 buttons, when I use the iterator to click the 5 buttons, the control is going out of the loop instead of clicking the second button.
Iterator<WebElement> button1 = T2.iterator();
while(button1.hasNext()) {
button1.next().click();
Thread.sleep(10000);
}
driver.findElement(By.id("button2 id")).click();
If I use the Thread.sleep()
, it's working fine. But I don't want to use that as its not the proper way.
The button2 id is also in enabled state, I wasn't able to use the Wait for the element to be enabled
. When the execution comes to the button1.next().click()
, i,mediately it's going to the next line, without completing the loop. If i print some text after the button1.next().click()
, the text gets printed 5 times. But don't know why the button is not clicked.
Even tried implicit wait, but no luck.
What is the best way to avoid such kind of issue?
Upvotes: 3
Views: 7244
Reputation: 38444
The proper way is to wait explicitly for the product to be added to the cart. Something changes on the page after the operation finishes, right? So wait for that change to occur! I don't know your webpage, obviously, but something along the lines:
// earlier
import static org.openqa.selenium.support.ui.ExpectedConditions.*;
// also earlier, if you want, but you can move it to the loop
WebDriverWait wait = new WebDriverWait(driver, 10);
Iterator<WebElement> button = T2.iterator();
while(button.hasNext()) {
// find the current number of products in the cart
String numberOfProductsInCart = driver.findElement(By.id("cartItems")).getText();
button.next().click();
// wait for the number of items in cart to change
wait.until(not(textToBePresentInElement(By.id("cartItems"), numberOfProductsInCart)));
}
Upvotes: 7