javascripttestingautomated-testscypresscypress-conditional-testing

How to skip failing part in Cypress test script


what is expected from the below code is get_plz_ChooseGroup will be skipped and not trigger a test failure if the element is not visible after 5000 seconds

Login_Page_POS.get_plz_ChooseGroup({ timeout: 5000 })
            .then(($element) => {
              if ($element.is(":visible")) {
                Login_Page_POS.chooseGroup(groupName)
              } else {
                cy.log("Element not visible after 5 seconds, skipping this part")
              }
            })
            .catch(() => {
              cy.log("Element not found after 5 seconds, skipping this part")
            })

and :

  this.plz_group_Label = "//span[contains(text(),'Please choose your group')]"
      get_plz_ChooseGroup() {
        return cy.xpath(this.plz_group_Label)
      }

fails at .catch(() => {:

_Login_Page_POS.default.get_plz_ChooseGroup(...).then(...).catch is not a function

Solution

  • If you search Cypress docs for .catch() you will find that there is no such command.

    The cy.xpath(this.plz_group_Label) command fails if there is no such element in the DOM.

    The way to do this is by polling for the element for 5 seconds using jQuery methods, which uses CSS selectors rather than xpath selectors.

    To poll you will need a recursive function/method, for example:

    const selector = 'span:contains("Please choose your group")'  // CSS selector
    
    get_plz_ChooseGroup(try = 0) {
    
      if (try = 50) return cy.wrap(null);  // indicate failure to find with null return
    
      const element = Cypress.$(selector)
      if (element.length === 0) {
        cy.wait(100)
          .then(() => {
            get_plz_ChooseGroup(++try)
          })
      }
      return cy.wrap(element)
    }
    

    The invocation would be

    get_plz_ChooseGroup().then($element => {
    
      // catch the element failure
      if (!$element) {
        cy.log("Element not found after 5 seconds, skipping this part")
        return
      }
    
      if ($element.is(":visible")) {
        Login_Page_POS.chooseGroup(groupName)
      } else {
        cy.log("Element not visible after 5 seconds, skipping this part")
      }
    }) 
    

    I have to say, this is not a very good way to test - what if the element isn't found? You will skip part of your test code, presumably it is important to run it every time you run the test.

    I suggest taking a look at How to write a test which explains the Arrange-Act-Assert pattern.