Return boolean in Cypress

79 Views Asked by At

I have function in another class file (following pageObject):

getElementExists(xpathSelector){
        cy.xpath(`count(${xpathSelector})`).then(count => {
            const exist = (count > 0) ? true : false
            console.log(exist)
            return cy.wrap(exist)            
        })  
    }

In another js, I try to use function:

basePage.getElementExists(XPath).then((fi) => {
       console.log(fi)
})

I get TypeError: Cannot read properties of undefined (reading 'then')

How can I return boolean in Cypress and use it further?

3

There are 3 best solutions below

0
Simon Ludders On BEST ANSWER

The xpath library is no longer used, but you can still evaluate xpathSelector with document.evaluate which is built into the browser.

getElementExists(xpathSelector) {
  return cy.document().then(document => {
    const result = document.evaluate(`count(${selector})`, document)
    const exists = !!result.numberValue   // 0 yields false, 1+ yields true
    return exists
  })
}
basePage.getElementExists(xpathSelector).then(exists => {
  console.log('exists', exists)
})

An example test:

cy.visit('https://example.com');

basePage.getElementExists('/html/body//h1')    // h1 heading is on the page
  .should('eq', true)                          // passes

basePage.getElementExists('/html/body//span')  // span is not on the page
  .should('eq', false)                         // passes
0
agoff On

Your variable is undefined because you aren't returning it from the getElementExists function. Additionally, because it will be used within a Cypress command chain, it doesn't need to be wrapped when it is returned.

getElementExists(xpathSelector){
        return cy.xpath(`count(${xpathSelector})`).then(count => {
            const exist = (count > 0) ? true : false
            console.log(exist)
            return exist          
        })  
    }
1
Carpenter On

cy.xpath() has been deprecated. The equivalent to cy.xpath(count(...)) in Cypress is its('length').

The following works in the latest Cypress versions:

getElementExists(selector) {
  return cy.get(selector).its('length').then(count => {
    const exists = !!(count > 0)
    return cy.wrap(exists)
  })
}

In the test:

basePage.getElementExists(path).then((exists) => {
  console.log(exists)
})

You can use page object models, but a Cypress custom command is simpler.

In cypress/support/commands.js

Cypress.Commands.add('elementExists', (selector) => {
  cy.get(selector).its('length').then(count => {
    const exists = !!(count > 0)
    cy.wrap(exists)
  })
}

In the test:

cy.elementExists(path).then((exists) => {
  console.log(exists)
})