我正在尝试验证针对特定用户的某些Web元素/按钮应隐藏在页面上的情况。我已经完成了一种方法的快速n脏实现来验证这一点,并想知道是否有更好的方法来做到这一点。请指教
public void ValidateThatButtonIsHidden(string button)
{
IWebElement theButton = null;
if (button.ToLower().Trim() == "submit an order")
{ theButton = FindElement(By.Id(_elementBtnId1)); }
else if (button.ToLower().Trim() == "validate order")
{ theButton = FindElement(By.Id(_elementBtnId2)); }
//Verifying that an element is not visible
Assert.False(IsELementVisible(theButton));
}
想法是用户可以调用此方法,并从他/她的测试中传递字符串以验证隐藏的元素。
答案 0 :(得分:1)
您可以使用Displayed
方法检查页面中元素的可见性。
如果该元素在页面中可见,则theButton.Displayed
将返回值为true,否则将为不可见元素写入false。
因此,您可以按以下方式更改断言
Assert.IsFalse(button.Displayed);
答案 1 :(得分:0)
您可以将InvisibilityOfElementLocated
类中的ExpectedConditions
方法与ElementExists
方法结合使用。这个想法是,如果元素存在于DOM中但仍然不可见,则必须将其隐藏:
By your_locator = By.Id("foo");
Assert.IsTrue(ExpectedConditions.ElementExists(your_locator) && ExpectedConditions.InvisibilityOfElementLocated(your_locator));
答案 2 :(得分:0)
这对我很有帮助。不仅适用于检查隐形性,还适用于启用/未启用,存在/不存在等:
private enum ElementStatus{
VISIBLITY,
NOTVISIBLE,
ENABLED,
NOTENABLED,
PRESENCE,
ABSENT
}
private ElementStatus isElementVisible(WebDriver driver, By by,ElementStatus getStatus){
try{
if(getStatus.equals(ElementStatus.ENABLED)){
if(driver.findElement(by).isEnabled())
return ElementStatus.ENABLED;
return ElementStatus.NOTENABLED;
}
if(getStatus.equals(ElementStatus.VISIBLITY)){
if(driver.findElement(by).isDisplayed())
return ElementStatus.VISIBLE;
return ElementStatus.NOTVISIBLE;
}
return ElementStatus.PRESENT;
}catch(org.openqa.selenium.NoSuchElementException nse){
return ElementStatus.ABSENT;
}
}
答案 3 :(得分:0)
我评估了这里提出的所有解决方案,但是面临着这样的挑战(我应该提到我们也有角度页面),有时实际上本应被隐藏的 Elements 缺失来自 DOM 。 由于我无法找到元素,因此我也希望该方法对于其他测试可重用/可扩展,以免我不得不测试另一个隐藏的按钮/元素。这就是我所做的,值得一提的是,我正在使用 Specflow 来参数化我的测试。
public bool IsElementPresent(By by)
{
try
{
driver.FindElement(by);
return true;
}
catch (NoSuchElementException)
{
return false;
}
}
public void ThatButtonIsHidden(string p0)
{
if (p0.ToLower().Trim() == "submit an order")
{
bool isBtnPresent = IsElementPresent(By.Id("btn1Id"));
Assert.IsFalse(isBtnPresent);
}
else if (p0.ToLower().Trim() == "validate order")
{
bool isBtnPresent = IsElementPresent(By.Id("btn2Id"));
Assert.IsFalse(isBtnPresent);
}
}
希望这会有所帮助。非常适合我处理这种情况。