0

I'm working on a cypress test that toggles a checkbox that toggles items which causes the button to appear and it click the button. The test itself works as intended for when there are items togglable. The case when there aren't any items that can be toggled, the assertion fails because the button doesn't show up. How would I write a test where it check if the button shows up after something is toggled or else log something when it doesn't appear.

The conditional doesn't actually work as it always hit hit the if even if the button doesnt exist so I'm sure that my if statement itself is wrong.

rody401
  • 99
  • 1
  • 5

1 Answers1

2

There is an add-on package called cypress-if which would be used like this

cy.contains('button', 'Create New')
  .if()
  .should('be.visible')
  .click()
  .wait(pageload)
  .else()
  .log('No toggable options available')

The .if() command goes before any .should(), so .should('be.visible') can run after the .if() - but maybe that gives you the wrong logic (depending on how the app works).

You can try adding the visible check as a parameter of the .if()

cy.contains('button', 'Create New')
  .if(':visible')
  .click()
  .wait(pageload)
  .else()
  .log('No toggable options available')

Using getCy()

getCy() appears not to be chained off cy, which makes it slightly tricky to use with if().

Essentially you would need to nest the code like this:

cy.contains('button', 'Create New')
  .if(':visible')
  .then($el => {

    cy.wrap($el).click()
      .wait(pageload)

    getCy('model')
      .should('be.visible')
      .find('.button')
      .should('be.disabled')

    ...
  
  })
  .else()
  .log('No toggable options available')
TesterDick
  • 3,830
  • 5
  • 18