Search code examples
javaselenium-webdriverxpathcss-selectorscucumber

How to wait for a user to login before checking they are successful using Selenium


I have written a cucumber scenario to complete the username and password fields, then click submit. Once submit is pressed, it should take the user to the homepage and check for an element to show they are logged in.

Currently, then final 'Then' part of the scenario fails as it says it cannot find the element #frontpage-header-wrapper - as if it is checking before the login has happened and the homepage has loaded.

What am I doing wrong here? This is the code I have currently:

Given("I am on the VLE login page", function(){
    this.driver = new Builder()
        .forBrowser('chrome')
        .build();
 
    this.driver.get('http://website.com');
});

When("I enter my credentials", function(){
    this.driver.findElement(By.id("username")).sendKeys("username1");
    this.driver.findElement(By.id("password")).sendKeys("password1");
    this.driver.findElement(By.id("loginbtn")).click(); //Clicking will then load the homepage
});

Then("I am logged in to the VLE", function(){
    this.driver.findElement(By.id("frontpage-header-wrapper")); //Once on the homepage, I want to find this element to show the user has logged in
});

Solution

  • When you execute this line of code:

    this.driver.findElement(By.id("loginbtn")).click(); //Clicking will then load the homepage
    

    The user gets logged in and the user's homepage gets loaded. So the element identfied with:

    this.driver.findElement(By.id("frontpage-header-wrapper")); //Once on the homepage, I want to find this element to show the user has logged in
    

    is not readily available within the DOM Tree


    Solution

    Once on the homepage to identify the visible element you need to induce WebDriverWait for the visibilityOfElementLocated and you can use either of the following locator strategies:

    • Using id:

      WebElement element = new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfElementLocated(By.id("frontpage-header-wrapper")));
      
    • Using cssSelector:

      WebElement element = new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#frontpage-header-wrapper")));
      
    • Using xpath:

      WebElement element = new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='frontpage-header-wrapper'")));