0

I want to try to click an ElementFinder, so that in case of error during click, the tests will be not marked as failed and no error will be placed on console.

Unfortunately, my method:

static tryToClick(elem: ElementFinder) {
    // I want to ignore all errors, just try to click and if not proceed
    if (elem.isPresent() && elem.isDisplayed() && elem.isEnabled()) {
        try {
          browser.wait(protractor.ExpectedConditions.elementToBeClickable(elem), 999).then(function() {
            elem.click().then(function() {try {} catch (error) {} } );
          });
        } catch (error) {}
    }
  }

still produces an error on the console:

  • Failed: stale element reference: element is not attached to the page document

thus I don't understand why it is not handled in the try-catch block.

matandked
  • 1,527
  • 4
  • 26
  • 51

1 Answers1

2

Your try-catch isn't working, because the error occurs inside the promise.

There are three ways to catch promise rejection:

  1. Use the .catch(...) function of a promise

    elem.click().catch((err) => { // Do some error handling stuff in here });
    
  2. Use the rejection-function of the .then(...)

    elem.click().then(() => {
        // Do something
    }, (err) => {
        //Do some error handling stuff in here
    });
    
  3. Use a try-catch in combination with async-await

    static async tryToClick(elem: ElementFinder) {
        // I want to ignore all errors, just try to click and if not proceed
        if (elem.isPresent() && elem.isDisplayed() && elem.isEnabled()) {
            try { 
                await browser.wait(protractor.ExpectedConditions.elementToBeClickable(elem), 999);
                await elem.click();
            } catch (error) {}
        }
    }
    
Batajus
  • 5,831
  • 3
  • 25
  • 38