Reputation: 4469
According to my many answers all over SE, selenium's driver.findElements()
should be returning an empty List<WebElement>
when it can't locate any elements that match the criteria. So why does this line:
items = driver.findElements(By.linkText("remove"))
throw an ElementNotFoundException
? For context: this line is in a loop, it works fine several times before throwing this exception when there are no more "remove" links left.
In particular, this answer is pretty explicit that this should give me an empty list.
EDIT:
Here's the whole loop that's causing the issue.
List<WebElement> items;
try {
items = driver.findElements(CartPage.itemInCart);
} catch (NoSuchElementException e) {
return;
} catch (Exception e) {
throw e;
}
while (items.size() > 0) {
List<WebElement> removeButtons = driver.findElements(CartPage.removeItem);
removeButtons.get(0).click();
click(CartPage.yesButton, "Confirm remove item");
items = driver.findElements(CartPage.itemInCart); // <--Exception here
}
Note the try
/catch
before the loop, that's what I was hoping to avoid using every single time I want to check is an element is visible.
Upvotes: 4
Views: 7322
Reputation: 3384
The exception occurs because you have removed the last element from the cart and there is no more element left to be identified with the given criteria:
Say initially Items had 5 elements in it during WHILE LOOP until items.size() > 1 loop will work fine, but when items.size() ==1; it will enter the loop and execute but at
click(CartPage.yesButton, "Confirm remove item");
last element will be removed and no such element will exist hence causing an exception because locator "CartPage.itemInCart" value is not present in DOM anymore.
Upvotes: 2