Customize the “Please fill in this field.” message?
Detect that this message is being displayed?
a. My client wants automated testing and so we need to test that missing values for required fields are enforced.
b. We have 80% automated testing coverage on the frontend, except for these field validations.
the code you posted shows an element with attributes. to check pseudoclasses existence or to access element properties you need to access the DOM with js, it can’t be done by just parsing the html.
in my previous link there are examples about accessing the validity property (with a different purpose thoug)
if you aim to test this by just parsing the html then checking for the existence of the required attribute (or other relevant validation attribute) is all you can do
I was able to get it to work from your directions. For future users trying to do the same automated testing, I leave my JavaScript and Cypress code here.
JavaScript
When the required field error is displayed, the following pseudo class should exist on the input element.
describe('Login Form Test', () => {
it('Prevent form submission if the required inputs are missing.', () => {
// Visit the page
cy.visit('https://my.app.com/login');
// Attempt to submit the form without filling in required fields
cy.get('form').submit();
// Check for invalid fields
cy.get('#input-email:invalid').should('exist');
cy.get('#input-password:invalid').should('exist');
// Check for invalid field message
cy.get('#input-email:invalid').then(($input) => {
expect($input[0].validationMessage).to.equal('Please fill in this field.');
});
cy.get('#input-password:invalid').then(($input) => {
expect($input[0].validationMessage).to.equal('Please fill in this field.');
});
});
});
Addendum: Getting the validity or validationMessage for a dropdown (multiselect) field is a bit more challenging. So documenting this for my (future) self and for the community.
For displaying the validationMessage of dropdown fields, WeWeb uses a hidden<input> element with the required attribute to trigger the browser’s built-in validation. This hidden input is the source of the “Please fill in this field” message. This is a clever trick that WeWeb uses to leverage the browser’s native validation of their dropdown field, which is a very custom implementation for us.
To interact with this field, I created a custom attribute for the dropdown named “ut-data” and gave it a name called “gender” for the gender dropdown. You can then access the fake/hidden input field this way.
cy.get('div[ut-data="gender"] .multiselect-fake-input:invalid').should(
"exist"
);
cy.get('div[ut-data="gender"] .multiselect-fake-input:invalid').then(
($input) => {
expect($input[0].validationMessage).to.equal(
"Please fill in this field."
);
}
);