When working on my automation script using Java with Selenium and the Page Object Model, I sometimes find it necessary to utilize Javascript Executor. This is because default WebDriver clicks can result in exceptions when elements are not found.
Within the framework's page where web elements are initialized, the code appears as follows:
public class MainPage {
WebDriver driver;
JavascriptExecutor executor = (JavascriptExecutor) driver;
@FindBy(xpath = "//*[@id='main_button']/div/span")
WebElement mainButton;
@FindBy(xpath = "//*[@id='login_button']/div/span")
WebElement loginButton;
// constructor initializes the elements
public MainPage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
// method for clicking mainButton using WebDriver
public void clickMainButton() {
WebDriverWait wait = new WebDriverWait(driver, 40);
wait.until(ExpectedConditions.elementToBeClickable(mainButton)).click();
}
// method for clicking loginButton using JS Executor
public void clickLoginButton() {
WebDriverWait wait = new WebDriverWait(driver, 40);
executor.executeScript("arguments[0].click();", loginButton);
}
While executing the script that interacts with the page, calling the clickMainButton(); method works correctly. However, calling the clickLoginButton(); method results in a null pointer exception:
java.lang.NullPointerException
at pages.MainPage.clickLoginButton(MainPage.java:55)
If I create an instance of the Javascript Executor inside the clickLoginButton(); method, it functions properly. My question is how to implement the Javascript Executor correctly within the Page Object Model without needing to create a new instance in every method?