Home > Software design >  Cypress how to check if an element contains a certain string
Cypress how to check if an element contains a certain string

Time:06-15

Cypress how to check if an element contains a certain string?

I use a custom check if element exists code to check if the element can be found (An error message) then I want to check if this element contains certain text? or could I use the java function of query selector?

         cy.validateIfElementExistsInDomAsBoolean('[data-testid=alert-content]').then(bool => { // checks error to file see how it works
              if (bool) {
                if(cy.contains('[data-testid=alert-content]', "Your basket has been updated. Please refresh the basket to continue.")){
                  console.log("refresh site")
                 }else{
                    console.log("different error")
                      }
             }else{
                cy.log("Checked for error no error found")
              }
            })

CodePudding user response:

Assuming validateIfElementExistsInDomAsBoolean correctly returns a boolean value true or false, you can do something like this:

cy.validateIfElementExistsInDomAsBoolean('[data-testid=alert-content]').then(
  (bool) => {
    // checks error to file see how it works
    if (bool) {
      cy.get('[data-testid=alert-content]')
        .invoke('text')
        .then((text) => {
          if (
            text ==
            'Your basket has been updated. Please refresh the basket to continue.'
          ) {
            cy.log('refresh site')
          } else {
            cy.log('different error')
          }
        })
    } else {
      cy.log('Checked for error no error found')
    }
  }
)

In case You have to do a partial string check, you can replace

if (text=='Your basket has been updated. Please refresh the basket to continue.')

with

if (text.toLowerCase().includes(
      'Your basket has been updated. Please refresh the basket to continue.')
)

CodePudding user response:

Potentially you can make your custom command return the text or empty string

Cypress.Commands.add('validateIfElementExistsInDomAsString', (selector) => {
  const $element = Cypress.$(selector);
  if ($element.length > 0) {
    return $element.text()
  } else {
    return ""
  }
})

cy.validateIfElementExistsInDomAsString('[data-testid=alert-content]')
  .then(error => {

    if (error === "") {
      cy.log("Checked for error no error found")
      return
    }

    if (error === "Your basket has been updated. Please refresh the basket to continue.") {
      console.log("refresh site")
    } else {
      console.log("different error")
    }
  })
    
  • Related