Prozorov
Prozorov

Reputation: 159

isDisplayed not locating an element

From my understanding when referring to web element and initialisation is done through PageFactory.init it will look for an element at the time when you referring to it, but in my case isDisplayed throwing NoSuchElementException.

I would like to just check if an element displayed yet, if yes do one thing if no do another and i end up doing spagetti code :

public CarParkBook addVehicleIfNotExist(Vehicle vehicle) {
    try {
        if (!carParkBook.vehicleInput.isDisplayed())
            carParkBook.vehicleInput.clear();
        carParkBook.vehicleInput.sendKeys(vehicle.getVehiclePlateNumber());
        carParkBook.addVehicleButton.click();
        return carParkBook;
    } catch (NoSuchElementException ex) {
        clickOnConfirmVehicleButton();
    }
    return carParkBook;
}

public class CarParkBook extends BasePage {

    private static CarParkBook carParkBook;

    @FindBy(xpath = "//input[@id='numberplate']")
    public WebElement vehicleInput;

    public static CarParkBook carParkBookInstance(WebDriver driver) {
        return carParkBook == null ? carParkBook = new CarParkBook(driver) : carParkBook;
    }

    public CarParkBook(WebDriver driver) {
        super(driver);
    }


public class BasePage {

protected final WebDriver driver;

public BasePage(WebDriver driver) {
    this.driver = driver;
    PageFactory.initElements(new AjaxElementLocatorFactory(driver, 5), this);
}

Upvotes: 1

Views: 153

Answers (1)

Gaj Julije
Gaj Julije

Reputation: 2183

It is lot easier to not use page factory in that case you can do a simle thing to check weathere element is displayed or not.

if( driver.findelements(By.xpath("whatever")).size>0)  // if true your element is displayed.

But if you use page factory try with the following code, i did not try but it should work

@FindBys(@FindBy(xpath=”whatever”)))
public List<WebElement> desiredElement;

then use same logic as above, just check

desiredElement.size()>0

Let me know does this help.

Upvotes: 1

Related Questions