How to check if an element exists and only then run a test with Cypress?

Viewed 280

I want to execute some function only when certain element is present using its data-test id.

Below is what I am trying to do:

cy.getByTestId('checkbox-id').then((el) => {
    if (el) {
        cy.tableSelectAll();
    }
}

Here I am expecting it to execute tableSelectAll() only if there is an element. But this fails saying it couldn't find an element with id "checkbox-id".

How can I fix this? Could someone please help me with this?

2 Answers

You can use the jquery method .attr to check the presence of the attribute data-testid.

cy.get('checkbox-id').then(($ele) => {
  if ($ele.attr('data-testid')) {
    cy.tableSelectAll()
  } else {
    //Do something else
  }
})

You want to follow this pattern Element existence

cy.get('body')
  .then(($body) => {
    // synchronously query from body
    // to find which element was created
    if ($body.find('[data-testid="checkbox-id"]').length) {
      // checkbox-id was found
      cy.tableSelectAll()
    }
  })
Related