How to explicitly wait while using page factory in Selenium?

7cart project picture 7cart project · Nov 9, 2017 · Viewed 7.2k times · Source

I'm going to organize an explicit wait in Selenium like this:

WebDriverWait = new WebDriverWait(driver,30);

WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(locator));

The problem is that I don't have the driver in my class, because I used the PageFactory, not a constructor in a test class:

MyClass myform = PageFactory.InitElements(driver, MyClass.class)

What is a good decision to organize explicit wait in this case?

Answer

Ben picture Ben · Nov 9, 2017

I would suggest that you use the PageFactory as intended and have a constructor for your class where you would like to use the explicit wait. Having a separation between the script and the page objects makes it much easier to work with in the future.

public class MyClass {

    WebDriverWait wait; 
    WebDriver driver; 
    @FindBy(how=How.ID, id="locatorId")
    WebElement locator; 

    // Construct your class here 
    public MyClass(WebDriver driver){
        this.driver = driver; 
        wait = new WebDriverWait(driver,30);
    }

    // Call whatever function you want to create 
    public void MyFunction(){
        wait.until(ExpectedConditions.presenceOfElementLocated(locator));
        // Perform desired actions that you wanted to do in myClass
    } 

Then in your test case use code to perform your test. In your example, the wait is contained inside the page.

public class MyTestClass {
    public static void main (string ... args){
        WebDriver driver = new FireFoxDriver(); 
        MyClass myForm = PageFactory.initElements(driver,Myclass.class); 
        myForm.MyFunction(); 
    }
}

This example was modeled after the example in the book Selenium WebDriver Practical Guide that can be found here here