0

我需要验证一个字段,假设用户名字段不应允许插入超过 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。在 cypress 中有没有办法做到这一点?

4

2 回答 2

1

假设这#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)
  ...
于 2021-04-25T20:22:47.133 回答
0

我在这里使用以下内容检查验证:

... // text60Characters = 60 个字符,例如 123467890...

cy.get(FIRST_NAME_INPUT).type(testdata.text60Characters); cy.get(FIRST_NAME_INPUT).invoke('val').its("length").should("eq", 50);

...

这对我有用。

于 2021-04-25T21:42:07.237 回答