简体   繁体   中英

Cypress how to check if an element contains a certain string

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")
              }
            })

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")
    }
  })
    

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.')
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM