skip to Main Content

When I try

cy.get('div.userId')

I want to add condition div.userId is exists/not in dom.

I am expecting not to fail test before checking existence of element in dom.

Like sometimes div.userId is not visible and cy.get(div.userId) fails but we ma need to click another element to make it visible. simple wanna use if-else statement upon this…

2

Answers


  1. Cypress does not recommend you write conditional tests like this. It would be preferable to write your tests to behave in a definite manner and control the application state so that you don’t have to deal with if/else. Before implementing something like the below, consider how you could make your test more determinant (mocking application data, for example.)

    You can search for a parent element to the div.userId, and then use JQuery functions (which do not have implicit assertions) to check if the div.userId exists.

    cy.get('parentElement')
      .then(($el) => {
        if ($el.find('div.userId').length > 0) {
          // code for if the element exists
        } else {
          // code for if the element does not exist
        }
      });
    
    Login or Signup to reply.
  2. cy.get(‘div.userId’).if(‘visible’).click()/trigger(‘mouseover).else().log(‘there is no userid in the dom element’)

    you have to install the if else plugin

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search