javascriptcypresscypress-conditional-testing

Cypress cy.its('length') does not work when single element appeared but works correctly for multiple elements


In Cypress, I am trying to write function to type in the editable field. If multiple elements found for the same locator, then enter the string in last editable field, else type the text in the detected editable field.

My below code works very well when multiple elements found for the same locator. But failed If there is single webelement located for locator.

module.exports. enterValue = (valueToType,ediatbleFieldLocator)=>{
    cy.log("Entering the  "+valueToType+"  in the editable field " +  ediatbleFieldLocator)
      cy.get(ediatbleFieldLocator).its(`length`). then($size=>{
        cy.log($size)
        if ($size === 1){
            cy.log("  editable field is found ")
            cy.get(ediatbleFieldLocator) .clear().should('be.empty')
            .should('be.enabled')
            .type(valueToType,{ log: false })
             }
        if ($size > 2) {
            cy.log(" multiple element of same locator is found ")
            cy.get(ediatbleFieldLocator)  .last() .clear().should('be.empty')
            .should('be.enabled')
            .type(valueToType,{ log: false })
        } else {
            throw new Error('Element is not found !');
        }
    })
}

The above code throws an error: enter image description here

Below code works good when single webelement is detected.

cy.get(ediatbleFieldLocator).clear().should('be.empty').should('be.enabled').type(valueToType,{ log: false })

I want to write function to handle all the possibilities like either single webelement detected or multiple. It should works. kindly please suggest..


Solution

  • If you always want the last element when multiple elements are found, you can simply use .last() and not have to worry about if one or more elements are found. The behavior will be the same.

    cy.get(ediatbleFieldLocator)
      .last()
      .clear()
      .should('be.empty')
      .and('be.enabled');