Not able to bypass a condition in cypress when it's not visible

85 Views Asked by At

In Cypress I'm simply trying to to close a filter using it's class "const filterRemoveElement = '.position-absolute > img';" But the problem is that if cypress found that element then it's passing the test case, if there are no filters applied then it's failing the test case, not going for else condition

cy.get(filterElement).then(($elements) => {
  if ($elements.length > 0) {
    cy.get('.d-inline-block').find('.dropdown-toggle').then(($filter) =>{
      if($filter.length > 1){
        cy.get(filterRemoveElement).then(($remove) => {
          if($remove.length > 0) {
            cy.get(filterRemoveElement).click({ multiple: true });
          } else {
            cy.log('No filter remove button present, skipping "remove filter" step.');
          }
        })
      } else {
        cy.log('No filter dropdown present, skipping "remove filter" step.');
      }
    })
  } else {
    cy.log('No filter section present, skipping "remove filter" step.');
  }
})
2

There are 2 best solutions below

0
Sam On

try below

cy.get(filterElement).then(($elements) => {
  if ($elements.length === 0) {
    cy.log('No filter section present, skipping "remove filter" step.');
    return;
  }

  cy.get('.d-inline-block .dropdown-toggle').then(($filter) => {
    if ($filter.length <= 1) {
      cy.log('No filter dropdown present, skipping "remove filter" step.');
      return;
    }

    cy.get(filterRemoveElement).then(($remove) => {
      if ($remove.length > 0) {
        cy.get(filterRemoveElement).click({ multiple: true });
      } else {
        cy.log('No filter remove button present, skipping "remove filter" step.');
      }
    });
  });
});
0
Aladin Spaz On

Generally speaking, you are going about the testing all wrong.

A good test has three steps - Arrange / Act / Assert.

"Arrange" means you set up the test page first so that you know what the page looks like before the "Act" part.

This way you end up with simple elegant tests that focus on the features of the page and how much code coverage your tests give you.

For example

it('removes a single filter', () => {

  // Arrange 
  // - set up a single filter (whatever that code looks like)
  cy.get(filterElement).should('have.length', 1)

  // Act 
  cy.get('.d-inline-block').find('.dropdown-toggle')
  cy.get(filterRemoveElement).click()

  // Assert
  cy.get(filterElement).should('not.exist')
})

Similarly for multiple filters, the changes are obvious.

Note, in your original code you missed the use-case of a single filter element.