In HTML5, form validation is a standard feature that validates data client-side before form submission, such as checking if required fields are filled or if input data meets format requirements. Typically, if validation fails, the browser displays a prompt indicating necessary corrections. However, these native browser pop-ups are not DOM elements, so they cannot be directly tested using traditional DOM operations.
Cypress, as a frontend automation testing framework, offers specific approaches for handling such cases. Below are several steps and techniques demonstrating how to test HTML5's built-in form validation with Cypress:
1. Triggering Validation
First, ensure the form triggers HTML5 validation. This is typically done by attempting to submit a form that does not meet validation criteria.
For example, if you have a required input field, you can attempt to submit an empty form:
javascriptcy.get('form').within(() => { cy.get('input[type="submit"]').click(); });
2. Asserting Validation Messages Correctly
Since native browser validation pop-ups cannot be directly selected or asserted, we need to confirm validation triggers through alternative methods. One approach is to check the validation state of input fields.
HTML5 introduces pseudo-classes such as :invalid, :valid, and :required, which can be used in Cypress to verify if fields are in the expected validation state:
javascriptcy.get('input:invalid').should('have.length', 1);
Additionally, you can check if input fields have specific attributes, such as the validationMessage attribute, which contains the current validation message.
javascriptcy.get('input:required').then(($input) => { expect($input[0].validationMessage).to.contain('Please fill out this field'); });
3. Handling Pop-ups with Plugins or Custom Commands
Although Cypress officially does not support handling native pop-ups directly, community plugins and methods can be used. For example, you can override native alert() and confirm() functions to control pop-ups.
javascriptcy.on('window:alert', (text) => { expect(text).to.contains('Please fill out this field'); });
4. Modifying Form Behavior for Testing
If the above methods do not meet your testing needs, you can modify the behavior of HTML form elements. For instance, you can prevent the default form submission behavior and manually check field validity, allowing error messages to be generated in the DOM for detection by Cypress.
javascriptcy.get('form').submit((e) => { e.preventDefault(); // Execute custom validation logic });
These are some basic methods for testing HTML5's built-in validation functionality. Each method has its applicable scenarios, and you should choose based on specific testing requirements.