Unable to locate nested text using XPath

Viewed 84

I am new to automation and am trying to test an unsuccessful login. On entering a wrong password an error popup window is displayed on website. I am trying to write a test to confirm the error text is displayed.

Code trials:

@Test
    public void IncorrectPasswordMessage() {

        boolean b=driver.findElement(By.xpath("//*[@id=\"errors\"]/h2")).isDisplayed();
        Assert.assertTrue(b);

    }

The HTML is below. How could I change my script to confirm the nested text "There are the following errors." is shown on the webpage?

<form id="login_form" action="/cs/form/customer-login" method="AJAX" class="cforms pad-top1 span6">
    <!--|cid=1400679170853|type=Forms_P|-->
    <div id="errors" style="">
        <h2>There are the following errors.</h2>
        <ul><li>The number and password you have entered do not match. Please enter it again.</li></ul>
    </div>
    <input type="hidden" name="_form_url" value="">
    <input type="hidden" name="_success_url" value="">
    <input type="hidden" name="_failure_url" value="">
</form>
1 Answers

The element is a AJAX element so to click() on the element you need to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following Locator Strategies:

  • cssSelector:

    @Test
        public void IncorrectPasswordMessage() {
            WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div#errors>h2")));
            // lines of code
            Assert.assertTrue(b);
        }
    
  • xpath:

    @Test
        public void IncorrectPasswordMessage() {
            WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='errors']/h2")));
            // lines of code
            Assert.assertTrue(b);
        }
    
Related