automationcypresscypress-conditional-testing

How to handle hidden elements in Cypress with if statement?


I have an element job-ad which is dynamic i want it to be handle when it’s displayed and not displayed

For example if .job-ad is displayed log me a text it’s Visible, but else log it’s hidden. I tried it with below approach but it keeps me throwing an error that the #JobAdCard is hidden (that’s where i want to show the ‘it’s hidden)

Here's my approach;

cy.get('.job-ad', {failOnStatusCode: false})
 .then(($jobAd) => {
    if ($jobAd.length > 0 && $jobAd.is(':visible')) {
       cy.log('JOB CARD IS VISIBLE');
    } else {
       cy.log('JOB CARD IS HIDDEN');
  }
});

and the error that i get; Timed out retrying after 1000ms: Expected to find element: .job-ad, but never found it.


Solution

  • cy.get('body').then((body) => {
      if (body.find('.job-ad').length > 0) {
          cy.log('JOB CARD IS VISIBLE')
      }
      else {
          cy.log('JOB CARD IS HIDDEN');
      }
    });