我需要验证一个字段,比如说用户名字段,不应该允许插入超过50个字符作为用户输入。我可以使用以下命令将文本(60个字符(插入该字段:
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*/
但在输入后,我需要检查字段上插入了多少个字符,或者字符的长度不应超过50。有没有办法在柏树上做到这一点?
假设#dwfrm_contactus_firstname
是一个输入元素,类似于这个
<input maxlength="50" />
您将从value
属性而不是text
属性读回文本。
你的测试可能看起来像这个
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));
})
您可以通过将子字符串增加到51来检查测试本身,然后它就会失败。
如果您想直接检查数字长度,您需要将主题从元素更改为文本,
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
})
为了更好地衡量,在测试输入时,首先清除它是有用的,
cy.get(FIRST_NAME)
.clear() // ensure empty input
.type(firstNameText)
...
我在这里使用了以下内容来检查验证:
//text60字符=此处有60个字符,如123467890…
cy.get(FIRST_NAME_INPUT(.type(testdata.text60个字符(;cy.get(FIRST_NAME_INPUT(invoke('val'(.its("length"(.hill("eq",50(;
这对我很有效。