cypress conditional testing skip to next line

Viewed 39

Hi there I'm new at cypress so I'm not sure if what I'm trying to write makes any sense. With the below, I would like to remove the cookies notification by clicking on it, but in case the cookies notification is not visible, I would like to skip this step and move to the next one.

//cookies notification close button
        it('cookies notification', () => {
          const $body = cy.get("body")
          if ($body.find('[class="pg-layer cookie pg-layer-open state-app-home"]'))
          {
            cy.get('[class="fa-fw far fa-times fa-1-5x mxn material-icons"]').click()
            
           }
           
           else {shouldSkip}
           
          })

The above function is not working, could anyone help out please? thanks

3 Answers

In the find part of the code add condition to check the length of that element which you want to check as follows, that should do the trick. eg.

if (body.find('some element locator').length > 0){
clickSomething
}

//cookies notification close button
        it('cookies notification', () => {
          const $body = cy.get("body")
          if ($body.find('[class="pg-layer cookie pg-layer-open state-app-home"]').length > 0)
          {
            cy.get('[class="fa-fw far fa-times fa-1-5x mxn material-icons"]').click()
            
           }
           
           else {shouldSkip}
           
          })

For conditional testing in Cypress, install the cypress-if package.

It's a major improvement over the officially documented way of doing what you want.

cy.get('[class="pg-layer cookie pg-layer-open state-app-home"]')  
  .if()
  .within($cookieLayer => {
    cy.get('[class="fa-fw far fa-times fa-1-5x mxn material-icons"]')
      .click()
  })

Basically, having .if() in the chain stops the previous cy.get() command from failing when the element does not exist.


BTW you can probably find a better selector for the the Cookie accept button, and shorten the test code a bit.

Maybe:

cy.get('[class="pg-layer cookie pg-layer-open state-app-home"]')  
  .if()
  .contains('button', 'Accept Cookies')
  .click()

You can't work with return values as you are doing in the first line of your test.

Solution: just delete that const body declaration and open a closure this way:

    it('cookies notification', () => {
      cy.get("body").then($body => {
      if ($body.find('[class="pg-layer cookie pg-layer- 
    open state-app-home"]').length > 0)
      {
        cy.get('[class="fa-fw far fa-times fa-1-5x mxn 
    material-icons"]').click()
        
       }
       
       else {shouldSkip}
       
      })
    })

Please read this chapter https://docs.cypress.io/guides/core-concepts/variables-and-aliases#Return-Values

Related