akshith
akshith

Reputation: 127

Pass a variable value out of the if statement

I just need to pass true for the button variable if the if condition is ok. Then i need to pass the test case if the button variable value is true. Can someone help me to fix this. This is what i have got so far.

cy.get('@checkSkipButton').then(checkSkipButton => {
    if (checkSkipButton) {
        cy.log("NOT CLICKABLE")
        cy.then(button = true)
        //cy.log(button)
        //return button;
        
        //cy.log(button)
        //return button
    
            }else{
                cy.log("CLICKABLE")
                button = False
                //return this
            } 

        
        }    )
        cy.log("value is"+button)
        button.should(have,value=true)
        
    }

Upvotes: 1

Views: 245

Answers (4)

Alapan Das
Alapan Das

Reputation: 18626

You were very close, the above will work fine with some minor changes.

let button //Declare it globally so that it can be accessed outside if
cy.get('@checkSkipButton')
  .then((checkSkipButton) => {
    if (checkSkipButton) {
      cy.log('NOT CLICKABLE')
      button = true //instead of cy.then directly update the value of button
    } else {
      cy.log('CLICKABLE')
      button = false
    }
  })
  .then(() => {
    cy.log('Value is: ' + button) //prints the button value
    cy.wrap(button).should('equal', true) //Asserts the button value
  })

Upvotes: 0

Nopal Sad
Nopal Sad

Reputation: 644

If you want to use button globally, you must wait for it's value to be set by using .then()

let button;    // undefined now and also later in the test if not wrapped in .then()

cy.get('@checkSkipButton').then((checkSkipButton) => {
  if (checkSkipButton) {
    cy.log('NOT CLICKABLE')
    button = true;
  } else {
    cy.log('CLICKABLE')
    button = false;
  }
})

cy.wrap(button).should('equal', true) // Error: expected undefined to equal true
                                      // neither true nor false, but original value (undefined)
                              
// Allow above cy.get() to process
cy.then(() => {
  cy.log('Value is: ' + button);        
  cy.wrap(button).should('equal', true) // passes
})

Upvotes: 1

TesterDick
TesterDick

Reputation: 10550

The code is close to working, but false instead of False and return the button to let you chain the .should() test.

cy.get('@checkSkipButton').then(checkSkipButton => {
  let button;
  if (checkSkipButton) {
    cy.log("NOT CLICKABLE")
    button = true;
  } else {
    cy.log("CLICKABLE")
    button = false;
  } 
  return button       // passes to should
}
.should('eq', true)

Upvotes: 2

I think this is the same logic

cy.get('@checkSkipButton')
  .then(checkSkipButton => !!checkSkipButton)  // convert truthy to true/false 
  .then(value => cy.log("value is" + value))
  .should('eq', true)

Upvotes: 1

Related Questions