2

I have a test case of my site with cypress. however the site, which is been built in vue.js has lets say 2 journeys. in one of them there is an button which I want to click. So, what I want to do is the following:

if ('button exists') {
  cy.get(#"button-class").click()    //basically click the button
}

If the button isn't there, which can be true for the second journey then carry on, as no button will be there.

Whatever I have tried so far failed. All I want is a simple if statement in cypress.

TesterDick
  • 3,830
  • 5
  • 18

2 Answers2

4

This became a lot easier with the release of cypress-if package

cy.get(#"button-class")
  .if()
  .click()

Update for Cypress v12

Recent internal changes in Cypress have made this package stop working.

Please see this issue Can we please overwrite query commands #25078 and register your "vote" if you like the package and wish it were fixed.

TesterDick
  • 3,830
  • 5
  • 18
0

You can get the parent element of the button, which should be displayed everytime and query for your button inside its then() callback

cy.get('css of always displayed parent').then($parent => {
    if ($parent.find('#button-class').length) {
        cy.wrap($parent).find('#button-class').click();
    }
});
PeaceAndQuiet
  • 1,692
  • 8
  • 13
  • i have no parent element. there are 2 -3 different div basically that they are rendered depending on the insurrer we choose. this choice is asyc. meaning that one time might be choosing insurer A and next time B or C. now on the next page not all the insurers have this button! thats why i need conditial rendering? inst anything simple? i did: if (cy.get(#button-class){ // code here } but cy.get(#button-class) isnt evaluating to true or false :( and thats what i need. something to tell me if the button is there or not! :( – A Bit Of Everything Oct 07 '22 at 12:36
  • The way you want to do it is unfortunately not compatible with how cypress commands are built. Each cypress command return a promise so `cy.get()` will never return true or false. Maybe you can try to replace `'css of always displayed parent'` by `'body'` – PeaceAndQuiet Oct 07 '22 at 14:57