捕获错误而不使Protractor测试失败(等待元素可见)



我的应用程序有一个只有在特定情况下才会出现的Terms and Conditions模式。如果出现模态,我希望Protractor测试单击"同意",如果没有出现,则不执行任何操作。

这是我的方法,我尝试等待元素出现,如果它没有出现,就会捕获错误。如果出现该按钮,则单击该按钮,测试通过。但是,如果该按钮没有出现,则测试失败,并显示"Element is taking too long…"(元素占用时间过长…(消息。

waitForAgree() {
var until = protractor.ExpectedConditions;
try {
browser.wait(until.visibilityOf(this.agreeTerms), 5000, 'Element taking too long to appear in the DOM');
this.agreeTerms.click();
this.continue.click();
} catch (e) {
console.log("not found");
}
}

我也尝试过以下方法。这给了我消息Failed: Cannot read property 'agreeTerms' of undefined

clickAgree() {
//browser.ignoreSynchronization = true;
this.agreeTerms.isPresent().then(function (isPresent) {
if (isPresent) {
this.agreeTerms.click();
this.continue.click();
}
else {
console.log("not found");
}
})
}

感谢您对这两个错误的任何帮助。

为了详细说明第一个方法不起作用的原因,我们应该注意,使用Promise而不调用.catch通常是个坏主意,因为大多数时候我们永远不知道哪里出了问题,而try/catch根本没有帮助。这也是您的备用方法成功的原因,因为您正在Promise上调用.catch

如果你有兴趣让你的第一种方法发挥作用,那么你应该使用async/await,类似于这样的东西:

async waitForAgree() {
var until = protractor.ExpectedConditions;
try {
await browser.wait(until.visibilityOf(this.agreeTerms), 5000, '...too long...');
this.agreeTerms.click();
this.continue.click();
} catch (e) {
console.log("not found");
}
}

注意函数名称前面的关键字async和对browser.wait的调用前面的await。请注意,这是ES6功能。

希望它能帮助

我会将web元素存储在列表中,如果size of list等于1(在这种情况下,我知道按钮存在,所以单击它(。如果该列表返回零,则打印失败消息。

我将使用findElements而不是findElement

这就是您可以定义列表的方式:

var elems = driver.findElements(By.xpath("your locator")); 

为了计算大小,你可以使用这个:

var keys = Object.keys(elems);
var len = keys.length  

之后:

if (len == 1){
this.agreeTerms.click();
this.continue.click();
}
else{
Do something here, button did not appear.
}

我尝试了第一个方法的替代方法,它很有效。我不完全确定为什么我问题中的第一个失败了,而这次成功了。如果有人想详细说明,请提前感谢。如果你只需要一种工作方法,这里:

waitForAgree() {
var until = protractor.ExpectedConditions;
browser.wait(until.visibilityOf(this.agreeTerms), 5000, 'Element taking too long to appear in the DOM')
.then(() => {
this.agreeTerms.click();
this.continue.click();
})
.catch((error) =>{
console.log("not found");
});
}

最新更新