-1

我正在使用量角器来自动化 Web 测试以及 async/await 模式。

假设我有一个元素仅在我第一次单击特定切换时出现。

问题是,当它出现时,我想点击它。

有没有办法等待这个元素,如果它出现我点击它,如果没有,我点击别的东西然后继续我的操作而不使用 try/catch 块

Si 它应该是这样的(请注意,这是假设的):

/*This will click on the toggle that might trigger the extra element to appear*/
await this.toggle.click()
const isExtraElementPresent = await browser.wait(ExpectedConditions.presenceOf(extraElement),2000);
if (isExtraElementPresent ){
    await extraElement.click();
}

我现在正在做的事情如下:

await this.toggle.click();
try {
    await this.extraElement.click();
    }
catch (error) {
    await console.log("Extra element didn't appear.");
    }
4

1 回答 1

0

try/catch是处理这种情况的唯一方法。

try {
  // wait for the element
} catch (error) {
  // do whatever if the element is not present
}

但是,您应该考虑避免它,原因如下

你的逻辑如下

  • 登录
  • 等待可能不存在的元素 2 秒
  • 尝试点击

在大多数登录尝试中,您的第二个项目需要 2 秒,因此几乎browser.sleep

遵循的正确模式是这样的

var EC = protractor.ExpectedConditions;
var welcomeMessagePresent = EC.presenceOf(welcomeMessageElement);
var firstLoginPopupPresent = EC.presenceOf(firstLoginPopup);
// Waits for either condition
await browser.wait(
  EC.or(welcomeMessagePresent, firstLoginPopupPresent), 
  5000,
  'neither condition satisfied'
);

所以它会等待条件之一。并且可以有任意数量的条件 - 1,2,3 ...在您的情况下,它是任何一个条件

于 2021-04-05T14:37:10.337 回答