Home > Enterprise >  Is there a way in cypress to accomodate cy.get(`[data-cy="${test}"]`).filter(':visibl
Is there a way in cypress to accomodate cy.get(`[data-cy="${test}"]`).filter(':visibl

Time:02-04

I have a code like

cy.get(`[data-cy="${test}"]`).filter(':visible').click({force: true})

it works for some tests but for some elements there is no "filter" and those works without .filter(':visible'), so i am trying to accomodate both function in a single code to keep it generic for all kinds of buttons. Is there a way to do it?

I have tried few steps like:

cy.get(`[data-cy="${test}"]`).filter(':visible'|| ':hidden').click({force: true})

not sure whether it is right or wrong but its definielt not working!!

CodePudding user response:

If you are using {force: true} then it doesn't matter if the element is visible or hidden, cypress will click it. So in my opinion you don't need the filter option.

cy.get(`[data-cy="${test}"]`).click({force: true})

Or, If you want to directly apply the OR condition in .filter you can do:

cy.get(`[data-cy="${test}"]`).filter(':visible,:hidden').click({force: true})

Or, If you want to use If-Else you can do something like this:

cy.get(`[data-cy="${test}"]`).then(($ele) => {
  if ($ele.filter(':visible')) {
    cy.wrap($ele).click()
  } else if ($ele.filter(':hidden')) {
    cy.wrap($ele).click({force: true})
  }
})
  •  Tags:  
  • Related