Cypress - Element not found

840 Views Asked by At

How can I overcome a situation when the element is not found. I am automating a form where intentionally I am giving a duplicate name so an error message will be shown "Limit Name already exist" based on that I have written

   add.limitName().type('Movie Limits') // Giving duplicate name "Movie Limits"

   cy.get('.has-error > .col-sm-6 > [data-bv-validator="remote"]').then((wizard) => {
       if(wizard.text().includes('Limit Name already exist.'))  // Duplicate Limit Name Check
       {
           add.limitName().clear()
           add.limitName().type('Movie TR Limits')   // Giving another Name
       }
     })

This works perfectly fine if its a duplicate value but if its not a duplicate value then this element wont be found and an error is thrown and the test fails. How can i write in such a way if its not duplicate it carries on and if it is the above code comes into action ?

5

There are 5 best solutions below

0
On

You can check the error class after the .type() command

add.limitName().type('Movie Limits') 
  .then($el => {

    if ($el.hasClass('has-error')) {

      cy.get('.has-error > .col-sm-6 > [data-bv-validator="remote"]')
        .then((wizard) => { ...
        });
    }
  });
0
On

Assuming the element with .has-class is not the <input> you type into, use .parent() to check if the class is present.

add.limitName().type('Movie Limits') 

cy.get('[data-bv-validator="remote"]')
  .parent()                            // up to ".col-sm-6"
  .parent()                            // up to element which (maybe) has ".has-error"
  .then($el => 

    if ($el.hasClass('has-error')) {

      cy.get('.has-error > .col-sm-6 > [data-bv-validator="remote"]')
        .then((wizard) => { ...
        });
    }
  })
0
On

It seems perfectly legit for the test to fail when the error is missing, but to answer your question

Split off the last selector and check it with jQuery (which does not cause a fail) instead of including it in the Cypress cy.get().

cy.get('.has-error > .col-sm-6')
  .then($col => {
    // test the last element with jquery by checking it's length
    if ($col.find('[data-bv-validator="remote"]').length === 0) {
      ...
0
On

Assuming that when there is no error the element .has-error itself won't exist in the dom. So you can do something like this:

cy.get('body').then(($body) => {
  if ($body.find('.has-error').length > 0) {
    //Element found
    cy.get('.has-error').should('include.text', 'Limit Name already exist.')
    add.limitName().clear()
    add.limitName().type('Movie TR Limits')
  } else {
    //Error element not found.Write further code.
  }
})
0
On

You should use another selector other than .has-error if that class may or may not exist.

cy.get('my-selector').then($el => {
  if ($el.hasClass('has-error')) {

    cy.get('.has-error > .col-sm-6 > [data-bv-validator="remote"]')
      .then(wizard => {
        ...
      })

  } else {
    ...
  }
})