Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cypress Click if item exist

Tags:

cypress

I need a way to easily trigger a click() event only if an element exist on page. the fact that the element (confirm modal dialog) itself exist is not an issue for my test, but this can stop next steps. so I want to click OK only if the dialog is shown.

I tried something like this, but it didn't work:

  cy.get('body').find("button[data-cy=sometag]").then(items => {
    if(items.length) {
       cy.get('button[data-cy=sometag]').click();
    }
  });
like image 324
Roey Zada Avatar asked Nov 18 '25 05:11

Roey Zada


2 Answers

If you want to test that the modal exists but don't want to fail the test if it doesn't, use a jQuery selector.

const found = Cypress.$('button[data-cy=sometag]').length 

Modals are likely to animate on opening, so you you will need to repeat the check a few times, which you can do in a function

function clearModal(selector, timeout = 1000, attempts = 0)
  if (attempts > (timeout / 100)) {
    return;                                  // modal never opened
  }
  if (!Cypress.$(selector).length)  {        // not there yet, try again
    cy.wait(100)
    clearModal(selector, timeout, ++attempts)
  else {
    Cypress.$(selector).click()             // modal is up, now close it
  }
}

clearModal('button[data-cy=sometag]')

If you use the find like this cy.get('body').find("button[data-cy=sometag]") this will fail always whenever the element is not present. Instead you can use the find command inside the If condition and check its length.

cy.get('body').then($body => {
    if ($body.find("button[data-cy=sometag]").length > 0) {
        cy.get('button[data-cy=sometag]').click();
    } else {
        //Do something
    }
})

Instead of body, you can also use the parent element of the element in question, which you know for sure is visible and present on the page every time.

like image 23
Alapan Das Avatar answered Nov 19 '25 17:11

Alapan Das



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!