Thursday, 5 June 2014

Custom wait for element function for web driver

Web driver does have inbuilt functions to wait for the presence or even visibility of element on screen. However, at time we come across situations where non of the built in methods really work.

So here below is a custom method that is designed to use with any type of selenium webdriver frameworks. Lets have a look at the method::


public static void waitForEelement(final By locator, int timeOut) {

        for (int second = 0;; second++) {

            if (second >= timeOut) fail("timeout waiting for element");

            try {

                 if ((getSelenium().getWrappedDriver().findElements(locator).size()) > 0){

                     break;

                }

                } catch (Exception e) {}

            try {

                Thread.sleep(1000);

            } catch (InterruptedException e) {

                 e.printStackTrace();

            }

        }

      

    }


This method can be called upon as follows:

waitForEelement(By.xpath("//div[@class='signin']"),60);

5 comments:

  1. Thank you for the article was very helpful.

    Test Automation

    ReplyDelete
  2. I have a small question .
    How does this method waitForEelement(By.xpath("//div[@class='signin']"),60);
    work if the Element changes random?

    Test Automation

    ReplyDelete
    Replies
    1. If it is a dynamically changing object, you need to externalize the object and store it to a variable and then pass that variable to the 'wait'

      For eg: if class name is dynamic, in this case, 'signin'. You need to get 'signin' by using getAttribute of class command and assign that to a variable say 'dynamicName' and pass it to 'wait' like below.

      waitForEelement(By.xpath("//div[@class='"+dynamicName+"']"),60);

      so that it will handle any value that is passed to the variable 'dynamicName'.

      Hope I could clear your doubt.

      Delete
  3. Your article about software testing is awesome. It helped me to understand the career prospects in software testing industry. software testing training in Chennai

    ReplyDelete