Reputation: 249
I am looking for an example for a verification that a javascript alert has taken place. I have a script that goes to a login page, and attempts to login to the system. I have a test case for a successful login, and I am trying to work on a failed login case. Any suggestions for automation best practices would be appreciated. So to boil my question down it is simply "How to I verify that this alert has happened on my webpage?"
HTML
<div class="alert">
The username and/or password entered are invalid.</div>
Test
[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."));
}
Wait Selenium
//Waiting for error to display
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(60));
Upvotes: 2
Views: 12228
Reputation: 249
This is the code that actually worked for the given alert, as Saifur pointed out the alert isn't really an alert. I was able to dig down to the class level and verify that the text appears on screen with the following code.
var errorMessage = driver.FindElement(By.XPath("//div[contains(@class, 'alert')]"));
Assert.IsTrue(driver.PageSource.Contains("The username and/or password entered are invalid."));
Upvotes: 1
Reputation: 16201
Try the following and assert if the expected text exists depending on the Testing framework and assertions you use.
string text = Driver.SwitchTo().Alert().Text;
I use NUnit assertion and in my case it looks like the following
string text = Driver.SwitchTo().Alert().Text;
Assert.IsTrue(text.Contains("The username and/or password entered are invalid."));
2nd edit: adding explicit wait
Try adding explicit wait
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."));
Upvotes: 3