javascriptif-statementcypresscypress-conditional-testing

How to skip a Cypress test based on an IF ELSE statement?


I want to skip a test case based on the IF ELSE statement. I'm sharing the code below but although it couldn't find the element rather than skipping, it's failing the test case then continues with the following tests. Do you have any suggestions on how to achieve skipping?

Thanks in advance!

it('verifies the release carousel', function () {
      cy.get("body").then($body => {
        //Checks whether release carousel is displayed and acts accordingly
        if ($body.find('[data-cy="release-heading"]').length > 0) {
          loginPage.releaseHeader()
                    .should('be.visible');

          loginPage.releaseImage()
                   .should('be.visible');

          loginPage.releaseTitle()
                   .should('be.visible');
        } else {
          this.skip()
      }})
    })

Note: I also checked this topic Skipping a test in Cypress conditionally and tried to edit my code as mentioned in the 1t answer but couldn't achieve :(

I asked ChatGPT too, which suggested using Cypress.runner.stop(); and this stops the whole test though.

enter image description here


Solution

  • The linked answer is a good one but the scenario is a bit complicated. Use the same pattern but check your conditional statement with the console.

    I would add the visibility test into the if() statement, because at the moment you only have an existence condition.

    it('verifies the release carousel', function () {
    
      //Checks whether release carousel is displayed
      const releaseHeadingVisible = Cypress.$('body')
        .find('[data-cy="release-heading"].is(":visible")').length > 0;
    
      console.log(releaseHeadingVisible)      // check and adjust condition
    
      if (!releaseHeadingVisible) {
        this.skip()
      }
    
      loginPage.releaseHeader().should('be.visible');
      loginPage.releaseImage().should('be.visible');
      loginPage.releaseTitle().should('be.visible');
    })