Search code examples
selenium-java

Find text from tags


I have the following html code from which I want to get the text: Nothing entered.

<div class="ng-tns-c170-53 ng-star-inserted ng-trigger ng-trigger-flyInOut ngx-toastr toast-warning" toast-component="" style="opacity: 1;">
<button type="button" aria-label="Close" class="toast-close-button ng-tns-c170-53 ng-star-inserted" style=""><span aria-hidden="true" class="ng-tns-c170-53">×</span></button><!----><!----><!----><div role="alert" class="ng-tns-c170-53 toast-message ng-star-inserted" aria-label="Nothing entered." style=""> Nothing entered. </div><!----><!----></div>

I tried to use this Java selenium code:

        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(timeout));
        WebElement nothingEnteredErrorMessage = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"toast-container\"]/div[1]/div")));
        assertEquals(nothingEnteredErrorMessage.getText(), "<Nothing entered.>");

But I get error:

org.opentest4j.AssertionFailedError: expected: <Nothing entered.> but was: <<Nothing entered.>>

Solution

  • You already selected the element correctly, the problem is in you assertion it should be:

    assertEquals("Nothing entered.", nothingEnteredErrorMessage.getText());
    

    The <> wrap is not required, and remember the first parameter of assertEquals is the expected value and the second is the actual, doing it in a reverse way can give you confusing feedback.