How to check if an HTML5 validation was triggered using selenium?

前端 未结 4 1818
执笔经年
执笔经年 2020-12-14 19:43

If testing my webapp using Selenium. All the form validation in the webapp is done using HTML5 form validations. Is there any way to assert if a form/input validation was tr

4条回答
  •  庸人自扰
    2020-12-14 19:54

    Attribute validationMessage will return the message, that will be showing if validation fails:

    WebElement username = driver.findElement(By.id("username"));    
    String validationMessage = username.getAttribute("validationMessage");
    

    If element has required attribute, browser will show the message after submitting the form:

    boolean required = Boolean.parseBoolean(username.getAttribute("required"));
    

    You can check whether entered value is valid:

    boolean valid = (Boolean)((JavascriptExecutor)driver).executeScript("return arguments[0].validity.valid;", username);
    


    Not: message text and validation is customizable. If you want to test customized validation and message.

    Here test code for custom validation(Java, TestNG):

    Assert.assertTrue(Boolean.parseBoolean(username.getAttribute("required")), "Username is required and message should be showin");
    Assert.assertEquals(username.getAttribute("validationMessage"), "My custom message", "Message text control");
    
    username.sendKeys("@vasy a^");
    Assert.assertTrue((Boolean)((JavascriptExecutor)driver).executeScript("return arguments[0].validity.valid;", username), "Username should not contain not special characters");
    

提交回复
热议问题