'Cypress testing element existence

I have an error with Cypress, i need to test for the presence of an element, i use cy.find(selector).length" but this command returns an error.

if (cy.find('.mdl-textfield__error').length > 0 || cy.find('.mdl-selectfield__error').length > 0) {

        }

Do you have an idea of the origin of the problem ?

Thanks in advance,



Solution 1:[1]

It happens because of incorrect usage. As documentation says: .find() requires being chained off a command that yields DOM element(s). Please go through cypress and jquery documentations for more detailed explanations.

Related to your code example, you have to locate the parent element(which usually is always rendered), then search for its descendants:

cy.get('.parentSelector').then($parent => {
    if ($parent.find('.mdl-textfield__error ').length > 0) {

    // your code

    }
})

Solution 2:[2]

Your exact usage would be a bit weird to actually use in Cypress. The closest equivalent would be a Cypress chain like...

/**
* Both `.should('exist')`s are implied by the `.get()`, but explicitly
* stating what you are doing is good.
*/
cy.get('.mdl-textfield__error').should('exist')
  .get('.mdl-selectfield__error').should('exist')
  // rest of your code

The above will work even if there are multiple elements matching those selectors. Additionally, the test will fail if either of those selectors does not yield any elements. That may not be your intended use, but Cypress does endorse conditional testing except under specific uses. (If you know you'll have these errors present, then just test that they are present!)

Solution 3:[3]

Aside from the basic syntax errors as mentioned, if you look at the DOM you'll see that the error elements are always present, so testing for length > 0 or .should('exist') does nothing useful.

If you want to check if errors occurred test the inner text(s)

cy.get('.mdl-textfield__error').invoke('text').then(textfieldError => {
  cy.get('.mdl-selectfield__error').invoke('text').then(selectfieldError => {

    if (textfieldError || selectfieldError) {
      ... an error has occurred in one of the fields
    }
  })
})

You can also check for the is-invalid class which is used to control the error message and the red color

cy.get('.mdl-textfield').then($textfield => {
  cy.get('.mdl-selectfield').then($selectfield => {

    if ($textfield.hasClass(is-invalid) || $selectfield.hasClass(is-invalid)) {
      ... an error has occurred in one of the fields
    }
  })
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alex Izbas
Solution 2 agoff
Solution 3 Fody