javascriptxpathautomationcypress

How can I skip part of a test if an element can't be found


How do I can skip the "if" part, if it doesn't work.

enter image description here

enter image description here

describe('test that XPath from task does not work and change non-breaking space', () => {
    it('passes', () => {
      cy.visit('http://uitestingplayground.com/nbsp')
      if (cy.xpath('//button[text()="My Button"]').click()) {
        cy.log('Button found and clicked.')
      }
      else {
        cy.xpath('//button[text()="My\u00a0Button"]').click()
        cy.log('Button found and clicked. But was problem with non-breaking space in XPath.')
      }
    })
})

Solution

  • You can do like this. Here length > 0 will check if the element is present in the DOM.

    describe('test that XPath from task does not work and change non-breaking space', () => {
      it('passes', () => {
        cy.visit('http://uitestingplayground.com/nbsp')
    
        cy.get('body').then(($body) => {
          if ($body.find('button selector').length > 0) {
            cy.xpath('//button[text()="My Button"]').click()
            cy.log('Button found and clicked.')
          } else {
            cy.xpath('//button[text()="My\u00a0Button"]').click()
            cy.log(
              'Button found and clicked. But was problem with non-breaking space in XPath.'
            )
          }
        })
      })
    })