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

前端 未结 4 1819
执笔经年
执笔经年 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 20:00

    Testing for the presence of the HTML5 attributes that are responsible for the validation is adequate enough. Actually triggering the browser-implementation of the validation is not really testing your work (but instead testing the browser itself), which might be nice but in my opinion is unnecessary. How to do that is already covered in the top answer. My answer is just to expand with a defence-in-depth approach to form-field validation.

    It is absolutely necessary that you have your own validation in addition to the HTML5 rules, for when HTML5 validation is not supported (or is bypassed).

    The first problem is that the HTML5 validation takes precedence and prevents you from testing your own validation. So how to approach this?

    Test HTML5 validation attributes are present

    To test it has been used, use assertAttribute:

    
        assertAttribute
        id=myFieldId@required
        
    
    

    If for some reason you're using the XML syntax required="required", you will need to assert the value is "required".

    Testing fallback validation

    JavaScript

    If your HTML5 validation prevents your JavaScript validation from returning errors, after you have asserted that the HMTL5 validation attributes were present, you can remove the HTML5 validation attributes to test the fallback JavaScript validation:

    
        runScript
        document.getElementById('myFieldId').removeAttribute('required')
        
    
    

    Now you can test your JavaScript validation. To remove email validation, you will need to set the field's type attribute to text:

    
        runScript
        document.getElementById('myFieldId').setAttribute('type','text')
        
    
    

    Test server-side validation

    Even when you use HTML5 validation and JavaScript validation, if you are submitting to a server, you will need to test your server validates these fields, too.

    Calling a form's submit() function will submit the form without calling any validation. Selenium's submit command does the same thing:

    
        submit
        name=myFormName
        
    
    

    After waiting for the next page to load, you can check the expected errors are present.

提交回复
热议问题