How to store dynamic elements in a selenium automation framework based on page object model?

586 views Asked by At

The page object model in Selenium has you create pageobject classes that represent pages. These classes would contain object locators as well as functions that are relevant for that page.

For example:

public class LoginPage(){

    @FindBy(id="user")
    WebElement username;


    @FindBy(id="pass")
    WebElement password;


    @FindBy(id="submit")
    WebElement submitButton;

    //various methods like login

}

The problem is when we have dynamic elements appearing on the page. For example, there's a link that will appear dynamically (say a chat link only if certain conditions are met).

What is the best practice for declaring such dynamic elements in the page class?

We cannot use @FindBy because that will cause class instantiation to fail if that element isn't present in the UI.

1

There are 1 answers

2
undetected Selenium On

When using page object model and you create pageobject classes that represent pages if you expect the element to be loaded through some AJAX which might not be present immediately on the page already as an example the email field you can use the WebDriverWait support with a normal locator factory as follows:

  • Code Block:

    package com.pol.mugen.PageObjects;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.support.FindBy;
    import org.openqa.selenium.support.PageFactory;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;
    
    public class LoginPage {
    
          WebDriver driver;
          public LoginPage(WebDriver driver)
          {
              PageFactory.initElements(driver, this);
          }
    
           @FindBy(id="user")
          public WebElement username;
    
          @FindBy(id="pass")
          public WebElement password;
    
          @FindBy(id="submit")
          public WebElement submitButton;
    
          public void doLogin(String username,String userpassword)
          {
              WebElement element = new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(LoginPage.getWebElement()));
              email.sendKeys(username);
              password.sendKeys(userpassword);
              signin.click();
          }
    
          public WebElement getWebElement()
          {
              return username;
          }
    
    }