For a graduation project, I am testing an online store using Selenium Webdriver and Java. I'm stuck in this part of the testing , where I have to check whether all search results (products) contains partucular word.
My search returns several pages of products. There is a pagination at the bottom of the page, but I don't know and can't check the exact number of pages, so I just click the [Next page] button while it is available.
So the promblem is that when I click the [Next Page] button at the bottom of the page, the page scrolls up, the previous products remain for about 1 second, and then are replaced with new ones from the next page. The page itself is not reloaded, only the previous products are replaced by the next ones in the corresponding block on the page. The block and products are element.
It works if I use Thread.sleep, but this is considered a bad decision. I can't figure out if there's any way I can use explicity wait (textToBePresentInElement, elementToBeClickable, visibilityOfElementLocated, presenceOfElementLocated don't suit) as in my other tests.
List<WebElement> products = driver.findElements(By.className(SearchPage.LABEL_PRODUCT_NAME));
for (WebElement product : products) {
Assertions.assertTrue(product.getText().toLowerCase().contains(SearchPage.textForSearchWithResults),
"Error. No " + SearchPage.textForSearchWithResults + " found.");
}
WebElement pagination = driver.findElement(By.xpath(SearchPage.BUTTON_PAGINATION_NEXT));
while (driver.findElements(By.xpath(SearchPage.BUTTON_PAGINATION_NEXT)).size() > 0) {
pagination.click();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
List<WebElement> productsOnTheNextPage = driver.findElements(By.className(SearchPage.LABEL_PRODUCT_NAME));
for (WebElement product : productsOnTheNextPage) {
System.out.println(product.getText());
Assertions.assertTrue(product.getText().toLowerCase().
contains(SearchPage.textForSearchWithResults.toLowerCase()),
"Error. No " + SearchPage.textForSearchWithResults + " found.");
}
}
How can I replace this Thread.sleep?
Two ideas...
Right after you click "next page", you mentioned there is a 1-second window that the previous product remains on the page.
Start checking for visibilityOfElementLocated() = false
on the previous product right after you click "next page".
Idea #1 might fail if your CPU is not fast enough to catch the previous product during that 1-second window. In that case, try forking a new worker thread to check for the previous product right before you click "next page". Then, after you click "next page", the master thread will wait for the worker thread to confirm that the previous product has disappeared.