3

as anticipated in the question, I'd like to know if is possible to attempt a click action on a button, but if it's not in the page then the test skip that action (without being stucked or throwing an error) and continue to the next one. To be more specific, I have a modal where I can add rows to a table, but what I'd like to do is to add a new row only if a given button in the modal is not present, while if it's present the action would be to press first on that button and then proceeding to add a new row.

I ask you if it's possible because I'd like to avoid conditional statements during the test. Just let me know, thank you in advance :)

Ciccios_1518
  • 435
  • 1
  • 6
  • 13

2 Answers2

4

You can check if the element is present then do something if not then do nothing or something else.

 const modal = page.locator('modal-selector');
    
 if (await modal.isVisible()) {
   // do thing
 } else {
   // do another thing
 }

Yevhen Laichenkov
  • 7,746
  • 2
  • 27
  • 33
  • But I don't need to close the modal. I need to check if a given button is present in the modal and if not, I keep the modal opened and proceed to add a new row to the table inside the modal. Also, I wondered if it was possible to avoid if statements. – Ciccios_1518 Oct 08 '21 at 12:47
  • Oh, I see. I've updated the answer. So, you don't the `closeModal` method, but everything in it is suitable for your case. No, you can't avoid if statement, you can replace it with a ternary operator but I don't think that would be a better solution. – Yevhen Laichenkov Oct 08 '21 at 16:17
1
const locator = page.locator("some selector");
if (locator.count() > 0) {
  // found locator, do something
} else {
  // not found, do something else
}
Jason Hu
  • 99
  • 6
  • 3
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. You can find more information on how to write good answers in the help center: https://stackoverflow.com/help/how-to-answer . Good luck – nima Oct 08 '21 at 11:33