2

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')
                }
            })
        }
TesterDick
  • 3,830
  • 5
  • 18
Solufer
  • 21
  • 1
  • 3
  • 7
  • I don't quite understand what you're asking. You want to take the value of the `[data-test="form-switch"]` element and assert on the `[data-test="item-undefined-email"]` element? – agoff Apr 07 '22 at 18:38
  • It would help if you could add the `isContain()` custom command code. – jjhelguero Apr 07 '22 at 19:16

2 Answers2

1

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)  
})
Fody
  • 23,754
  • 3
  • 20
  • 37
0

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
  }
})
Alapan Das
  • 17,144
  • 3
  • 29
  • 52
  • I tried, but says: "Timed out retrying after 4000ms: expected '' to have attribute 'aria-checked'" – Solufer Apr 07 '22 at 19:11