I am working on cloudbase project which is having user authentication module. User can be authenticated to system using user credentials and also with using OAuth authentication.
I am automating this with Selenium but when I am trying to click on 'sign-in' button it does not work,
#BeforeTest
public void setUp()
{
driver = new FirefoxDriver();
driver.get("Application URL");
driver.manage().window().maximize();
}
#Test
public void enterCredentials()
{
driver.findElement(By.id("cred_userid_inputtext")).sendKeys("email address");
driver.findElement(By.id("cred_password_inputtext")).sendKeys("password");
driver.findElement(By.id("cred_sign_in_button")).click();
}
I have tried same using sendKeys(Keys.ENTER) and with sendKeys(Keys.RETURN)
Also tried using Actions
{
WebElement signIn_button = driver.findElement(By.id("cred_sign_in_button"))
Actions enterSignIn = new Actions(driver);
enterSignIn.moveToElement(signIn_button);
enterSignIn.click();
enterSignIn.perform();
}
For some reason, on some pages Firefox seems to require special treatment for Click(). I solved it this way (in C#, but Java should be similar):
// special workaround for the FirefoxDriver
var actions = new Actions(driver);
actions.MoveToElement(element);
ToolBox.DisableTimeout(testParams);
actions.Release().Build().TryPerform();
ToolBox.EnableTimeout(testParams);
actions.MoveToElement(element);
actions.Click().Build().Perform();
Explanation: I explicitly call Release() before calling Click(). Sometimes it's necessary, sometimes it isn't. If it is not necessary, then calling Release() ends up in waiting until the implicit timeout (if you have any) is over and then raising an exception. That is why I temporarily disable the timeout when calling Release() and also why I wrap it in a TryPerform() method, in order to ignore the exception. A look inside my TryPerform() method:
public static bool TryPerform(this IAction action)
{
try
{
action.Perform();
}
catch (Exception)
{
return false;
}
return true;
}
I know, there are no extension methods in Java, but you can probably solve this similarly.
Some times sleep before click will simulate click correctly. like
Thread.sleep(3000);
driver.findElement(By.id("cred_sign_in_button")).click();
If above one does not works, as you already tried with all locators and Actions, so try with java script executor
WebElement element = driver.findElement(By.id("cred_sign_in_button"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
Thank You,
Murali
Try this,
WebElement element = driver.findElement(By.id("cred_sign_in_button"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
[enter link description here][1]executor.executeScript("arguments[0].click();", element);
Visit Here
You can try explicit wait with expected conditions
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(By.id("cred_sign_in_button"))).click();
Related
I need to wait for a specific loader to complete loading once the button has been pressed, please take a look at the following image below:
As you can see from the image above, once the button has been pressed the ajax loader appears inside the button.
I have created the following selector to locate the button:
//form[contains(#id, 'messageform')]//button/span
Currently accepting the request (Clicking on the button) fails my test case as the script continues to the next test steps without waiting for the loader to complete.
I have tried the following and more, with no luck:
Injecting JS to wait for the page to fully load.
ExpectedCondition<Boolean> expectation = driver -> ((JavascriptExecutor) driver).executeScript("return document.readyState").toString().equals("complete");
ExpectedConditions.invisibilityOf(element)
WebDriver driver = getDriver();
WebDriverWait exists = new WebDriverWait(driver, timer);
exists.until(ExpectedConditions.refreshed(
ExpectedConditions.invisibilityOf(element)));
Any ideas?
You should use .stalenessOf() to wait until an element is no longer attached to the DOM.
Something like this (tweak to your case):
WebElement somePageElement = driver.findElement(By.id("someId"));
WebDriverWait wait = new WebDriverWait(webDriver, 10);
// do something that changes state of somePageElement
wait.until(ExpectedConditions.stalenessOf(somePageElement));
And the good thing is you don't have to handle any exceptions.
Alternatively, you can also create a method and handle exceptions like so:
public static void WaitForCommission (WebDriver driver) throws Exception {
for (int second = 0; second++) {
if (second >= 30) fail("timeout");
try {
if (IsElementActive(By.id("someElementID"), driver))
break;
} catch (Exception e) {}
Thread.sleep(1000);
}
}
private static boolean IsElementActive(By id, WebDriver driver) {
WebElement we = driver.findElement(id);
if(we.isEnabled())
return true;
return false;
}
I am having a problem with my Assertion, or rather with the "time" the assertion is being executed. So, the assertion is working as it should, however, it is going too fast, as it is executing without waiting for the page it should be targeting to load. Which means that the assertion is failing the test.
Having this in mind, I tried searching around how to add a "wait" to the assert to make it wait for the page to load before running, but with no success.
So, would anyone, please be able to help with this, as in how would I code so, that the assert "waits" for the page to load and then executes?
I've tried adding the wait to the header method, i tried adding the wait to the test script, but no success.
public class test1 extends DriverSetup{
//Here we are setting the method to use the homePage
private HomePage homePage = new HomePage(getDriver());
//Here we are setting the method logInPage
private AuthenticationPage authenticationPage = new AuthenticationPage(getDriver());
//Here are setting the method CreateAccountPage
private CreateAccountPage createAccountPage = new CreateAccountPage(getDriver());
//Here we are setting the method to access the Website HomePage with the driver
private void accessWebsiteHomePage (){
getDriver().get("http://automationpractice.com/index.php");
}
#Test
public void CreateAccount() {
accessWebsiteHomePage();
//Log in
homePage.logInBut();
//Authentication page "Create a new account" box
authenticationPage.setCreateAccountEmailAddress(emailGenerator.Email());
authenticationPage.CreateAccountButtonClick();
Assert.assertEquals("CREATE AN ACCOUNT", createAccountPage.HeaderCheckRightPage());
The assert should be targeting the "CREATE AN ACCOUNT" page, but it is targeting the "AUTHENTICATION" page, which comes before it, hence the test fails as the "actual" value being printed is the "AUTHENTICATION" page, not the "CREATE AN ACCOUNT" page.
You need to use an explicit wait. Here is one that will wait for the title to be equal to something:
private ExpectedCondition<Boolean> titleIsEqualTo(final String searchString) {
return driver -> driver.getTitle().equals(searchString);
}
You can make it more reliable by forcing the case of what you want to match like this:
private ExpectedCondition<Boolean> titleIsEqualTo(final String searchString) {
return driver -> driver.getTitle().toLowerCase().equals(searchString.toLowerCase());
}
You would then need to put the following in before your assertion:
WebDriverWait wait = new WebDriverWait(driver, 10, 100);
wait.until(titleIsEqualTo("CREATE AN ACCOUNT"));
I'm making the assumption that by header you mean the page title since you haven't shown the code that collects the header.
*Edit*
A non-lambda version of the above ExpectedCondition is:
private ExpectedCondition<Boolean> titleIsEqualTo(final String searchString) {
return new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driver) {
return driver.getTitle().toLowerCase().equals(searchString.toLowerCase());
}
};
}
Trying to send data in table element (cell). Verified ID, Xpath, CssSelector and none them is wrong.Even, put timeout till page load. Even verified the iFrame (Already switchTo current iFrame).
No such element found error pops up every time. Not sure if I need to switchTo iFrame again after page load?
I tried all the possible ways but not pass through. I really appreciate any suggestions or new direction to think.
Thank you in advance.
Run my script for better insight where its failing.
public class SapDijon
{
WebDriver driver;
JavascriptExecutor jse;
public static void main(String[] args) throws Exception
{
SapDijon sapObj = new SapDijon();
sapObj.invokeBrowser();
sapObj.initializeSapDijon();
sapObj.ForecastME59();
}//End of Main
public void invokeBrowser()
{
System.setProperty("webdriver.chrome.driver", "U:\\Research Paper\\Selenium\\Drivers\\Chrome\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
}
public void initializeSapDijon() throws Exception
{
Thread.sleep(1200);
driver.get("http://dijon.cob.csuchico.edu:8041/sap/bc/gui/sap/its/webgui/?");
driver.findElement(By.id("sap-user")).sendKeys("H5");
Thread.sleep(1200);
driver.findElement(By.id("sap-password")).sendKeys("Onsjhjsa1087");
Thread.sleep(1200);
driver.findElement(By.id("sap-client")).clear();
Thread.sleep(1200);
driver.findElement(By.id("sap-client")).sendKeys("485");
Thread.sleep(1200);
driver.findElement(By.id("LOGON_BUTTON")).click();
}
public void ForecastME59() throws InterruptedException
{
driver.switchTo().frame("ITSFRAME1");
Thread.sleep(800);
driver.findElement(By.xpath("//td[#id='tree#105#4#1']//span[#class='lsSTStatusImg lsMirrorRtl lsSTStatusIcon urSTExpClo urCursorClickable']")).click();
Thread.sleep(800);
Actions action = new Actions(driver);
WebElement md61 = driver.findElement(By.xpath("//span[#id='tree#105#6#1#1#i']"));
action.doubleClick(md61).perform();
driver.findElement(By.id("M0:46:::4:2-imgSymb")).click();
driver.findElement(By.id("M0:46:::4:26")).sendKeys("HH-F");
driver.findElement(By.id("M0:50::btn[0]")).click();
Thread.sleep(6000);
driver.manage().timeouts().pageLoadTimeout(4, TimeUnit.SECONDS);
driver.findElement(By.xpath("//span[#id='tbl5732[1,8]_c-r']/input[#id='tbl5732[1,8]_c']")).click();
driver.findElement(By.xpath("//span[#id='tbl5732[1,8]_c-r']/input[#id='tbl5732[1,8]_c']")).sendKeys("100");
}
}//End of Class
After " action.doubleClick(md61).perform()" switch back from frame to default content and again switch to the available iframe.
To move back to the parent frame, you can either use switchTo().parentFrame() or if you want to get back to the main (or most parent) frame, you can use switchTo().defaultContent();
The issue persists because of a new window opened and the script was unable to find the element. The solution is to switch to a newly opened window to find element locator.
ArrayList tabs = new ArrayList (driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
I have automation scenario that sometimes the system return javascript alert and sometimes not at all. I don't know what the cause of this, probably the network issue. I already create the alert handler for this:
public boolean isAlertPresent() {
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.alertIsPresent());
return true;
}
I call this in one of my step that sometimes appear alert:
public WSSPage enterAndSearchContent(String title) throws InterruptedException {
waitForElementTextWithEnter(searchTextField, title);
while (isAlertPresent()){
Alert alert = driver.switchTo().alert();
alert.dismiss();
break;
}
return PageFactory.initElements(driver, WSSPage.class);
}
The problem is when the alert doesn't show up, it will give me NoAlertPresentException, and the automation result will be failed. I want the code to move on if the alert doesn't happen by moving to the next line, in this case it will just return PageFactory.initElements(driver, WSSPage.class);
Can you help me provide a better code from this?
Thanks a lot.
JavascriptExecutor worked for you. Just take care that you should execute it before clicking the event which invoke alert.
((JavascriptExecutor) driver).executeScript("window.confirm = function(msg) { return true; }");
Note :- do not use it after clicking on event which invoke alert confirmation box. Above code by default set the confirmation box as true means you are accepting/click on ok on all confirmation box on that page if invoked
Hope it will help you :)
You can modify the method isAlertPresent as given below and try it. It may help you.
public boolean isAlertPresent() {
try{
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.alertIsPresent());
return true;
}
catch (NoAlertPresentException noAlert) {
return false;
}
catch (TimeoutException timeOutEx){
return false;
}
}
You can include that particular exception in try catch. Then the exception will be catched and will not through any error and your execution will continue.
Also create a implicit wait to handle this with less timestamp.
I know there are several threads regarding this topic, but I am not necessarily looking for a solution, but rather an explanation. I work on a very large automation suite that tests a web application via mobile phones using browserstack. My stability is very low.. and it is due to this error getting thrown at me! Occasionally it will work and occasionally it will not.. I can not use Actions because Browserstack does not support that.. WHY does this error exist and has anyone had any success it working around it. I always wait for an object using wait.until(ExpectedConditions), but sometimes this does not work well enough. I cant quite catch it as an exception since it is an Unknown error. Also, our standards do not allow for a Thread.sleep(). Any ideas? Thank you so much
And here is a screen of some code..
You are waiting for a WebElement to be clickable, then again you are finding a list of WebElements and clicking the first element.
This does not guarantee that you are clicking the element you waited for it be clickable.
public void waitAndClickElement(WebElement element) {
driverWait.until(ExpectedConditions.elementToBeClickable(element)).click();
}
In your case,
public void clickImageView() {
driverWait.until(ExpectedConditions.elementToBeClickable(listImageView)).click() ;
}
Element is normally not click able due to following reasons .
Html is loading and client is still receiving updates from server
When Scrolling
It can be due to some object is overlapping target
problem 3 can not be resolved you need to fix your code in this wait i wait for HTML to ready and then verify is it click able or not this has eliminated such exceptions from my code
how ever i made a solution for problem 1 and 2 you can simply use my custom wait before clicking . call this function
public static void waitForElementPresent(final By by, int timeout,WebDriver driver)
After this if you are using browser other then chrome then call Scroll to that object this would fix you problem
Code
public static void waitForElementPresent(final By by, int timeout,WebDriver driver) {
waitForPageLoad(driver);
WebDriverWait wait = (WebDriverWait)new WebDriverWait(driver,40).ignoring(StaleElementReferenceException.class);
/* wait.until(new ExpectedCondition<Boolean>(){
#Override
public Boolean apply(WebDriver webDriver) {
WebElement element = webDriver.findElement(by);
return element != null && element.isDisplayed();
}
}); */
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
wait.until(ExpectedConditions.presenceOfElementLocated(by));
wait.until(ExpectedConditions.elementToBeClickable(by));
WebDriverWait wait2 = new WebDriverWait(driver, 40);
wait2.until(ExpectedConditions.elementToBeClickable(by));
}
//wait for page to laod
public static void waitForPageLoad(WebDriver driver) {
ExpectedCondition<Boolean> pageLoadCondition = new
ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
}
};
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(pageLoadCondition);
}
This is due to the speed at which selenium runs. It will try and find elements before the page has loaded, thus resulting in this error.
For the code sample you provided, the .until() returns the WebElement you are waiting for. You can use the code below to click it rather than scraping the page again.
public void clickImageView()
{
driverWait.until(ExpectedConditions.elementToBeClickable(listImageView)).click();
}