量角器 - 尝试单击一个元素并忽略所有错误

Protractor - try to click an element and ignore all errors

我想尝试单击一个 ElementFinder,以便在单击期间发生错误时,测试不会被标记为失败,并且不会在控制台上放置任何错误。

不幸的是,我的方法:

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) {}
    }
  }

仍然在控制台上产生错误:

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

所以我不明白为什么它没有在 try-catch 块中处理。

您的 try-catch 不工作,因为错误发生在 promise 中。

可以通过三种方式捕获 promise 拒绝:

  1. 使用承诺的.catch(...)功能

    elem.click().catch((err) => { // Do some error handling stuff in here });
    
  2. 使用.then(...)

    的拒绝函数
    elem.click().then(() => {
        // Do something
    }, (err) => {
        //Do some error handling stuff in here
    });
    
  3. 结合使用 try-catchasync-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) {}
        }
    }