试图等待一个预期的元素消失,无法捕捉到这个错误

时间:2015-08-23 04:18:56

标签: angularjs jasmine protractor

我的量角器jasmine测试中有以下辅助函数

this.waitForExpectedElementToBeInvisible = function (expectedElement, timeout) {

    if (timeout === undefined) {
        timeout = 3000;
    }

    var EC = protractor.ExpectedConditions;
    return browser.wait(EC.invisibilityOf(expectedElement), timeout).then(function (element) {
        return element;
    });
};

大部分时间都很好,但有一段时间......元素已经过去了。我收到这样的错误:

NoSuchElementError: No element found using locator: By.cssSelector(".my-class")
麻烦的是,这打破了测试用例。我尝试将其包装在试试中但无济于事。

try {
      return this.waitForExpectedElementToBeInvisible(expectedElement, timeout);
} catch(err){
    throw err + " " + expectedElementCSS;
}

我认为,因为这是一个承诺的事情......我永远不会抓住错误..我如何抓住承诺及其错误?

1 个答案:

答案 0 :(得分:3)

您添加的try / catch只会在创建承诺时处理异常。您希望在解析承诺时(或在其解析器中)处理异常。正如@sirrocco所指出的,除了catch处理程序之外,大多数promise API(包括基于Webdriver的Protractor)都允许then处理程序,以便在解析期间处理异常。

return browser.wait(EC.invisibilityOf(expectedElement), timeout)
   .then(function (element) {
       return element;
   })
   .catch(function (err) {
       // check if the error is a NoSuchElementError and ignore it if so
       // otherwise re-throw it
       if (err.name === 'NoSuchElementError') { // There may be a better way to do this ...
          return null;
       }
       throw err;
   });

您通常不想使用.then(successCB, failCB)方法,因为successCB中的错误不会传递给failCB(它们会传递给依赖.catch }})。