Reputation: 95
I need to verify that a field, let's say the username field is should not allow more than 50 characters to be inserted as user input. I can insert text (60chars) to this field using the below:
const FIRST_NAME = '#dwfrm_contactus_firstname';
cy.get(FIRST_NAME).type('123456789012345678901234567890123456789012345678901234567890');
/* here i want to get the length of the text which is under the FIRST_NAME input field with a check that it should be equal to 50*/
but after typing it, I need to check how many characters are inserted over the field or the length of the characters should not exceed 50. Is there any way to do this in cypress?
Upvotes: 0
Views: 5488
Reputation: 95
I have used the following to check the validation here:
... // text60Characters = 60 characters here like 123467890...
cy.get(FIRST_NAME_INPUT).type(testdata.text60Characters); cy.get(FIRST_NAME_INPUT).invoke('val').its("length").should("eq", 50);
...
and this worked for me.
Upvotes: 0
Reputation:
Assuming that #dwfrm_contactus_firstname
is an input element, something like this
<input maxlength="50" />
you would read back the text from the value
property not the text
property.
Your test might look like this
it('ensure first name limits entry to 50 char', () => {
const firstNameText = '123456789012345678901234567890123456789012345678901234567890';
cy.get(FIRST_NAME)
.type(firstNameText)
.should('have.value', firstNameText.substring(0,50));
})
You can check the test itself by increasing substring to 51, it should then fail.
If you want to check the numeric length directly, you need to change the subject from the element to the text,
it('ensure first name limits entry to 50 char', () => {
const firstNameText = '123456789012345678901234567890123456789012345678901234567890';
cy.get(FIRST_NAME) // subject is <input> element
.type(firstNameText)
.invoke('val') // change subject to input's value
.should('have.length', 50); // assert the length property is 50
})
For good measure, when testing an input it's useful to clear it first,
cy.get(FIRST_NAME)
.clear() // ensure empty input
.type(firstNameText)
...
Upvotes: 2