Home > Software engineering >  How can I write if-else conditions in cypress according to element's value?
How can I write if-else conditions in cypress according to element's value?

Time:04-08

enter image description hereHow can I run this function, according to the value change of element with if-condition?

 assertSwitch(){
    
            cy.get('[data-test="form-switch"]').invoke('attr','value').then(($switchOnOff) =>{
                
            if($switchOnOff == true){
                    cy.isContain('.item-undefined-switch[data-test="item-undefined-email"]', 'true')
            }else{
                    cy.isContain('.item-undefined-switch[data-test="item-undefined-email"]', 'false')
                }
            })
        }

CodePudding user response:

You can do something like this:

cy.get('[data-test="form-switch"]').then(($ele) => {
  if ($ele.attr('val') == 'true') {
    cy.get('button[data-test="form-switch-input"]').should(
      'have.attr',
      'aria-checked',
      'true'
    )
    //Add something here
  } else {
    cy.get('button[data-test="form-switch-input"]').should(
      'have.attr',
      'aria-checked',
      'false'
    )
    //Add something here
  }
})

CodePudding user response:

The problem is both switches have the same data-test, so Cypress starts to get confused

cy.get('[data-test="form-switch"]')
  .eq(0)                              // pick one
  .invoke('attr','aria-checked')      // this attr indicates checked state
  .then(($switchOnOff) => {
                
    if($switchOnOff === 'true') {  // note adjustments here

      cy.isContain('.item-undefined-switch[data-test="item-undefined-email"]', 'true')  
    } else {
      cy.isContain('.item-undefined-switch[data-test="item-undefined-email"]', 'false')
    }
})

Or all switches

cy.get('[data-test="form-switch"]')
  .each(($switchOnOff) => {
    const value = $switchOnOff.attr('aria-checked')
    cy.isContain('.item-undefined-switch[data-test="item-undefined-email"]', value)  
})
  • Related