4

I am trying to do a conditional statement on cypress to check if the login link in the header is Sign in or Account or a class and then click on it.

The if condition is not working.

cy.get('header').then((header) => { 

if (header.find('Sign in').length > 0) { 
    cy.contains('Sign In')
    .click({force:true})  

} else if (header.find('Account').length > 0) {
    cy.contains('Account')
    .click()

} else {
    cy.get('.navUser-item--account .navUser-action').click()

}
})

I expect if Sign in found then it will click else if the Account is available then it will click else it will check by the class.

always doing the last else condition

there is Account text and still it applied the last else condition

Another code structure and now it always apply the first condition no matter what

desertnaut
  • 57,590
  • 26
  • 140
  • 166
Sam
  • 613
  • 1
  • 7
  • 12
  • What is happening that you do not expect to happen? & have you read the conditional testing docs? https://on.cypress.io/conditional-testing#Element-existence – Zach Bloomquist Apr 05 '19 at 18:49
  • i didn't understand what do you mean by "What is happening that you do not expect to happen?" & Yes i did go through the conditional testing doc – Sam Apr 05 '19 at 19:54
  • Are you getting an error? What's not working with the code you provided? – Zach Bloomquist Apr 05 '19 at 19:58
  • The following If X, then Y, else if A, then B, else Z my condition is A and it should execute B but no matter what is the condition it always executes Z – Sam Apr 05 '19 at 20:09
  • 1
    @ZachBloomquist i added some screen shots and i even changed the code. thank you for putting the time to help me – Sam Apr 05 '19 at 20:24

1 Answers1

4

The following code worked for me.

cy.get('header').then(($a) => { 
        if ($a.text().includes('Account')) {
            cy.contains('Account')
            .click({force:true})
        } else if ($a.text().includes('Sign')) { 
            cy.contains('Sign In')
            .click({force:true})  
        } else {
            cy.get('.navUser-item--account .navUser-action').click({force:true})
        }
    })
desertnaut
  • 57,590
  • 26
  • 140
  • 166
Sam
  • 613
  • 1
  • 7
  • 12