赛普拉斯循环输入

Cypress looping through input

我想做一个测试 (cypress) 来遍历输入并在每个输入字段中键入值,但我遇到了错误。任何人都可以帮助我吗? 糟糕,您似乎正试图在 运行 父命令之前调用子命令。

    <div class="content__form">
     <div class="formcolcontainer">
      <div class="formcol">
       <div class="formrow">
        <input type="text" id="fname" class="forminput">
        <label for="fname" class="formlabel"> FName</label>
       </div>
       <div class="formrow">
        <input type="text" id="lname" class="forminput"> 
        <label for="lname" class="formlabel"> LName </label>
       </div>
     </div>
    </div>

submitFormData(fname, lname){
        
        const inputFields = {
            Fname: fname,
            Lname: lname,
        }
        cy.get('.formrow')
          .find('input')
          .then(input =>{
              cy.wrap(input).each((field, value) =>{
                  cy.find(inputFields[`#${field}`]).type(inputFields[`${value}`])
              })
        })      
    }

你可以直接做这样的事情。您可以创建一个包含名字和姓氏的数组,并使用它们的索引位置直接在 type 中使用它们。

let inputFields = ['fname', 'lname']

 cy.get('.formrow').find('input').each(($ele, index) => {
   cy.wrap($ele).type(inputFields[index])
 })

你可以这样做,使用inputFields来驱动测试

const inputFields = {
  Fname: { id: 'fname', value: 'Fred' },
  Lname: { id: 'lname', value: 'Smith'},
}

cy.get('.formrow').each(($row, index) => {
  cy.wrap($row).find('label').then($label => 
    const inputSelector = `#${inputFields[label.text()].id}`;
    const value = inputFields[label.text()].value;
    cy.get(inputSelector).type(value);
})

错误信息的意思是

cy.find(inputFields[`#${field}`])

不正确,因为 .find() 不能用作链中的第一个命令。

你会改用

cy.get(inputFields[`#${field}`])

获取 id 的选择器也会不同

cy.get(`#${inputFields[field]`)

这样的事情可能会奏效,直接使用 <label> 文本来获取要输入的值

//earlier
const fname = 'John'
const lname = 'Jones'

const inputFields = {
  Fname: fname,
  Lname: lname,
}

cy.get('.formrow')
  .find('input')
  .each(($input, index) => {
    cy.wrap($input).sibling('label').invoke('text').then(label => 
      const value = inputFields[label.trim()];
      cy.wrap($input).type(value);
    })
  })

或者,循环遍历 inputFields 而不是使用 .each()

const inputFields = {
  fname: 'Tim',
  lname: 'Turner',
}

for (const key in inputFields) {
  const value = inputFields[key]
  cy.get(`.formrow input#${key}`)   // one input only, no need for .each()
    .type(value)
}

// Verify form fields
cy.get('.formrow input').eq(0).should('have.value', 'Tim')      // passes
cy.get('.formrow input').eq(1).should('have.value', 'Turner')   // passes