Alerts: How to assert a given paragraph



  • Using WebDriver and JUnit 4.11. I'm attempting to find an alert and assert the body of the alert paragraph.

    My code is:

    @carriann public void dNameField(){
    
        WebElement nameField = chrome.findElementByCssSelector("input.t-textInput-A[name='name']");
        nameField.clear();
    
        List elements;
        elements = chrome.findElements(By.className("logMessage.error"));
    
        Set foundAlerts = new HashSet();
    
        for(WebElement e : elements){
            foundAlerts.add(e.getTagName());
        }
    
        Assert.assertTrue("This should be an error message", foundAlerts.contains("An error has occurred : Value must be a Number."));
    

    I receive a java.lang.AssertionError: in the stacktrace.

    In the DOM before an alert is thrown this is this class which holds all the error logs that are produced in the session.

      Once I have managed to simulate an alert by clearing all data from a particular field, the alert is thrown in this class

      <ul class="logContainer t-logs-A">
      <li class="logMessage error" id="l1392048208775" style="display: none;">
      <header>
      <p>error!</p>
      <p class="closeBtn"></p>
      </header>
      <p>An error has occurred : Value must be a Number.</p>
      </li>
      </ul>
      

      The id is dynamically created so when I attempt to 'copy xpath' I'm supplied with //*[@id="l1392048208775"]/p which is no good.

      The alerts that are thrown all remain in the DOM as I can visibly see them, although they are hidden as they fade out from the UI after a couple of seconds.

      Any suggestions on how to go about this, please?


    • QA Engineer

      Why not use the selenium Alert switchto method and gettext?

      Alert alert = driver.switchTo().alert(); 
      String text = alert.getText(); 
      alert.dimiss(); 
      


    Suggested Topics

    • 2
    • 2
    • 2
    • 2
    • 2
    • 2
    • 2
    • 2