Search code examples
javaselenium-webdriverdata-driven

How to verify specific web element on different page in login module


In my application when user login first time then on first page username is displayed (data driven approach using @factory). But if user logs out and log in again then a new pages comes with following text.

You're signed out now.
Click here to sign in again.

My question is how to check if this text -'Click Here' present then click on it and do same actions as mentioned in login function.

I tried to implement if-else block to check if this webelement is displayed then click on it and do same action as in login function. But it is giving error that

org.openqa.selenium.NoSuchElementException: Cannot locate an element using xpath=//a[@href='/Account/Login']
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html

Though I'm successfully able to achieve my result by specifying this element to click in Logout function. But when finally my test gets finished it always clicks on it.

 @FindBy(xpath="//a[@href='/Account/Login']")
WebElement clickHere;

//function to check

if (clickHere.isDisplayed())
      {   
          clickHere.click();
          username.sendKeys(strUsername);
          nextBtn.click();
          password.sendKeys(strPassword);
          loginButton.click();
          System.out.println("Successfully Logged");
      }
      else
          {

          username.sendKeys(strUsername);
          nextBtn.click();
          password.sendKeys(strPassword);
          loginButton.click();
          System.out.println("Successfully Logged");
          }

Please suggest a solution to check in login function everytime.


Solution

  • clickHere.isDisplayed() is giving NoSuchElementException as the element is not present on the UI on which you are trying to find it.
    So, to solve your problem you can fetch the list of the element through pagefactory and then can find the size of that list, if the size is greater than 0, it means the element is present on the page else the element is not present.

    You need to make the following changes in your code and it would work fine then:
    You need to fetch the element list using:

    @FindAllBy(xpath="//a[@href='/Account/Login']")
    List<WebElement> clickHere;
    

    And make the following changes in your code:

    if (clickHere.size()>0){   
          clickHere.get(0).click();
          username.sendKeys(strUsername);
          nextBtn.click();
          password.sendKeys(strPassword);
          loginButton.click();
          System.out.println("Successfully Logged");
     }
     else{
          username.sendKeys(strUsername);
          nextBtn.click();
          password.sendKeys(strPassword);
          loginButton.click();
          System.out.println("Successfully Logged");
     }