conditional-statementscypresscypress-conditional-testing

How do you make a conditional test if an element exists in Cypress?


There is a lot online about testing if an element exists, but i can't find anything really specific that could help in my case.

For context, I am working on a website that has certain elements in them (like a todo list). I want to write a method/function called editItem which filters inside a searchbar for the itemName and then clicks on the filtered item.

The problem is, if something is already inside the searchbar for some reason I can not use the function .clear() to clear the text inside the searchbar. So I've tried to work around that and now I am using the inbuilt "x"-button that clears the searchbar on click.

The problem here is I need to implement an if-Condition that checks if the "x"-button is shown, but I don't know how to implement this.

In pseudocode:

if (searchbar.exists) searchbar.click()

Solution

  • Using https://github.com/bahmutov/cypress-if this sort of test becomes very easy.

    Examples for your button (depends on if the button is hidden or removed from DOM)

    cy.contains('button', 'x')
      .if(':visible')
      .click()
    
    // or
    
    cy.contains('button', 'x')
      .if('exists')
      .click()
    

    However

    It's still better to know the state of the page at point in the test, otherwise you can end up with false-positive results.

    Always test the command before the .if() command to make sure it's actually valid.