我正在寻找一个示例来验证是否发生了 JavaScript 警报。我有一个进入登录页面并尝试登录系统的脚本。我有一个成功登录的测试用例,并且正在尝试处理失败的登录用例。任何有关自动化最佳实践的建议将不胜感激。因此,归根结底,我的问题很简单:“如何验证此警报是否发生在我的网页上?”
HTML
<div class="alert">
The username and/or password entered are invalid.</div>
测试
[Test]
public void failedCustomerLogin()
{
//Finding the customer login link and clicking it
var customerLogin = driver.FindElement(By.Id("Homepage_r2_c14"));
customerLogin.Click();
Assert.AreEqual("http://stage.blank.net/login", driver.Url);
var userName = driver.FindElement(By.Id("username"));
userName.SendKeys("badCustomerName");
var Pasw = driver.FindElement(By.Id("password"));
Pasw.SendKeys("BadPassword");
var submit = driver.FindElement(By.Id("btnSubmit"));
submit.Click();
//TODO: need to find failed method
string errorText = driver.SwitchTo().Alert().Text;
Assert.IsTrue(errorText.Contains("The username and/or password entered are invalid."));
}
等等 Selenium
//Waiting for error to display
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(60));
最佳答案
尝试以下操作并断言预期文本是否存在,具体取决于您使用的测试框架和断言。
string text = Driver.SwitchTo().Alert().Text;
我使用NUnit断言,在我的例子中它看起来像下面
string text = Driver.SwitchTo().Alert().Text;
Assert.IsTrue(text.Contains("The username and/or password entered are invalid."));
第二次编辑:添加显式等待
尝试添加显式等待
Driver.FindElement(By.TagName("test")).Click();
//Make sure the click above generates the alert
String text = (new WebDriverWait(Driver, TimeSpan.FromSeconds(10))).Until(d => d.SwitchTo().Alert().Text);
Assert.IsTrue(text.Contains("The username and/or password entered are invalid."));
关于c# - Selenium C# 查找警报并验证文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29565643/