Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (19.7k points)

I am trying to automate some test cases using Java and Selenium WebDriver. I have the following scenario:

  • There is a page named 'Products'. When I click on 'View Details' link in the 'Product' page, a popup (modal-dialogue) containing the details of the item appears.
  • When I click on the 'Close' button in the popup closes and the page automatically refreshes (the page is just reloading, the contents remain unchanged).
  • After closing the popup I need to click on the 'Add Item' button on the same page. But when WebDriver trying to find the 'Add Item' button, if the internet speed is too fast, WebDriver can find and click the element.

  • But if the internet is slow, WebDriver finds the button before the page refresh, but as soon as the WebDriver click on the button, the page refreshes and StaleElementReferenceException occurs.

  • Even if different waits are used, all the wait conditions become true (since the contents in the page are same before and after reload) even before the page is reloaded and StaleElementReferenceException occurs.

The test case works fine if Thread.sleep(3000); is used before clicking on the 'Add Item' button. Is there any other workaround for this problem?

1 Answer

0 votes
by (62.9k points)

There are three ways to solve this, you can use any of these or combine them: 

1.) Immediately after creating the Selenium web driver instance, set implicit wait : driver.manage().timeouts().implicitlyWait(). This will tell the driver, the amount of time it should wait when finding an element if it is not immediately present after the page is loaded. 

2.) After page navigation, you'd have to call JavaScript return document.readyState until "complete" is returned. It means that the document (i.e. the .java file) is now parsed and loaded.

Sample code in C# is shown below: 

new WebDriverWait(driver, MyDefaultTimeout).Until(

    d => ((IJavaScriptExecutor) d).ExecuteScript("return document.readyState").Equals("complete"));

Java:

 

new WebDriverWait(firefoxDriver, pageLoadTimeout).until(

          webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));

3.) After performing step 2, check if the URL matches the pattern you expect.

To know more about Selenium, you can go through the Selenium course page by Intellipaat.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...