1

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()
TesterDick
  • 3,830
  • 5
  • 18
WirbleWind
  • 11
  • 1

1 Answers1

2

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.

Fody
  • 23,754
  • 3
  • 20
  • 37
  • First thanks for the answer, but that wasn't really what I was looking for. I need an if statement. If(button exists) then click on it. Then rest of the code should run. – WirbleWind Sep 26 '22 at 20:13
  • The `if()` command is the way to do it in a Cypress chain, It'll do exactly what you described. – Fody Sep 26 '22 at 21:09
  • Oh wow ok, i didn't even see it. But is there any way of doing it without installing anything external? – WirbleWind Sep 27 '22 at 07:27