how can I validate whether values entered in a new form is reflected correctly in edit form - selenium

I am trying to automate a website which is mainly dealing with Forms. I have entered values in new form and I need to validate whether it is reflected back correctly in edit form.
In New form I have tried like :
WebElement FN = driver.findElement(By.id("ctl00_ctl41_g_1fc852c8_32cb_4220_80ee_2af21b671f9e_ff21_ctl00_ctl00_TextField"));
FN.click();
FN.sendKeys("abc");
In the edit form code:
if(FN.getAttribute("value").equals("abc"))
System.out.println("First Name is matching with new form");
else
System.out.println("First Name is not matching with new form");
and I am getting error like
Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document(Session info: chrome=57.0.2987.110)
Thanks in advance .

You need to reinitialize the FN Webelement once you are at edit form, as the previous FN Webelement will become stale as soon as you move away from new form. Hence, try following:
FN = driver.findElement(By.id("ctl00_ctl41_g_1fc852c8_32cb_4220_80ee_2af21b671f9e_ff21_ctl00_ctl00_TextField"));
if(FN.getAttribute("value").equals("abc"))
System.out.println("First Name is matching with new form");
else
System.out.println("First Name is not matching with new form");
Let me know, if you have any further queries.

Possibly, you are having exception at FN.sendKeys("abc");. When you click on the element before going to edit mode, the element is also changing. That's why you are having that exception.
I suggest, after clicking on the FN element have locator for textfield afresh and use sendkeys() method on it.
To know about this type of exception this might help you:
http://darrellgrainger.blogspot.com/2012/06/staleelementexception.html

Related

How to find prompt by Selenium

Does anybody know how to find this type of element by Selenium? (to validate its presence or text)?
I tried to catch it as alert (swithToAlert()) but it doesn't work. Any ideas? It is also can not be inspected as element and I can't find it in Elements. Thank you in advance.
This uses HTML5 form validation. This is created by the browser, and does not exist in the DOM. Therefore Selenium cannot see this.
You can access this using JavaScript. Here is a brief code sample:
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
WebElement field = driver.findElement(By.tagName("input")); // your input box
if (!(Boolean) jsExecutor.executeScript("return arguments[0].validity.valid;", field)) {
return (String) jsExecutor.executeScript("return arguments[0].validationMessage;", field);
}
The entire API is documented.
element.validity.valid
Returns true if the element's value has no validity problems; false otherwise.
So this popup is displayed if this returns false, but only after clicking Submit on the form.

Cant insert text - a msg that the element is not visible is displayed

I run automation on a site that after I click on a button and a screen of PayPal is opened for inserting details. The PayPal is opened in another tab. I added a syntax that move the testing to the relevant tab and then I insert a syntax that checks that the "email input" field exists (to check that it is really goes to the correct tab) - and the result of this test :- field exists.
Then - I add a syntax for the same field to insert the email and the test is failed - the text is not inserted and there is a msg that the field is not visible.
No need to do scroll because the filed is in the top of the screen.
What can I do in this case?
This is the relevant code:
String oldTab = driver.getWindowHandle();
comOps.clickOrChose(PLS.buyButton);
Thread.sleep(4000);
ArrayList<String> newTab = new ArrayList<String> (driver.getWindowHandles());
newTab.remove(oldTab);
driver.switchTo().window(newTab.get(0));
comOps.verifyElementExist(PLP.payPalEmail);
comOps.insertText(PLP.payPalEmail, "paypal-buyer#makeitleo.com");
The reason you get this error message is that the element apparently exists but is not visible when you try to enter text to it. There are a lot of possible reasons why the element is not visible.
Given that a new tab is opended a probable reason is that the page (and its elements) is still loading. If this is the case, you need to wait for the visiblity of the element, e.g. using this piece of code (before inserting text):
WebDriverWait wait = new WebDriverWait(driver, 300); //waiting up to 5 minutes
ExpectedCondition<WebElement> condition =
ExpectedConditions.visibilityOf(PLP.payPalEmail);
wait.until(condition);
Note: that this solution assumes that PLP.payPalEmail is of type org.openqa.selenium.WebElement. If it is of type org.openqa.selenium.By use visibilityOfElementLocated(By locator).
Telling from your code snippet, I assume that comOps is an object of a class wrapping all Selenium actions. So, it is a good idea to place the above code in some method inside that class which could look like this:
public void verifyElementVisible(WebElement element) {
WebDriverWait wait = new WebDriverWait(driver, 300); //ToDo: use configurable timeout
ExpectedCondition<WebElement> condition =
ExpectedConditions.visibilityOf(element);
wait.until(condition);
}
and call it like this
comOps.verifyElementVisible(PLP.payPalEmail);

<Select> Tag is not working for selecting value in dropdown

I am facing an issue where dropdown has tag. but still I am unable to select value in dropdown and it is throwing exception. I am able to get dropdown values but unable to select
Here is complete details
URL : https://semantic-ui.com/modules/dropdown.html
Testcase: Select multiple values in Skill dropdown.( Find attachment for exact field on web page.
WebDriver driver = new FirefoxDriver();
driver.get("https://semantic-ui.com/modules/dropdown.html");
driver.manage().timeouts().implicitlyWait(10L, TimeUnit.SECONDS);
WebElement Dropdown = driver.findElement(By.name("skills"));
Select sel = new Select(driver.findElement(By.name("skills")));
List<WebElement> Options = sel.getOptions();
System.out.println(Options.size());
for(int i=0;i<Options.size()-1;i++) {
driver.findElement(By.xpath("//*[#id=\"example\"]/div[4]/div[1]/div[2]/div[4]/div[1]/div[8]/div")).click();
System.out.println(Options.get(i).getAttribute("value"));
if(Options.get(i).getAttribute("value").equalsIgnoreCase("angular")||Options.get(i).getAttribute("value").equalsIgnoreCase("Graphic Design")||Options.get(i).getAttribute("value").equalsIgnoreCase("HTML")) {
Thread.sleep(6000);
sel.selectByIndex(i);
}
}
}
Exception:
Exception in thread "main" org.openqa.selenium.ElementNotInteractableException:
Please help to suggest for this.
Your drop down is a simulated drop down by css, not a HTML native drop down: Select. So you can not operate it as native drop down.
After look into the HTML code of your dropdown, there is an embed native drop down, but it's always invisible no matter you expand options or not. Selenium can't operate on invisible element(But you can read value/attribute from it), that's why the exception you met.
Actually all options come from the div class="menu", so you should click the option from div class="menu" as below screenshot show:
Code to resolve your problem:
// click arrow down to expand options
driver.findElement(By.cssSelector("select[name='skills'] + i")).click();
// choose option: Angular
driver.findElement(By.xpath("//div[contains(#class, 'multiple')][select[#name='skills']]//div[.='Angular']"));

How to edit element in table with selenium?

I'm trying to edit value of element that placed it the table on
this page.
I'm using this code:
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://samples.gwtproject.org/samples/Showcase/Showcase.html#!CwCellTable");
WebElement firstName = driver.findElement(By.xpath("//*[#id=\"gwt-debug-contentPanel\"]/div[2]/div/div[2]/div/div[3]/div/div/div/table/tbody/tr[1]/td/table/tbody[1]/tr[1]/td[2]/div"));
firstName.click();
firstName.clear();
firstName.sendKeys("test");
It says:
"Element must be user-editable in order to clear it."
How i can edit this element?
Also i have troubles with "Category" field on this page. I'm trying to select each of them successively. Doing this with:
WebElement category = driver.findElement(By.xpath("//*[#id=\"gwt-debug-contentPanel\"]/div[2]/div/div[2]/div/div[3]/div/div/div/table/tbody/tr[1]/td/table/tbody[1]/tr[1]/td[4]/div/select"));
category.sendKeys("Businesses");
category.sendKeys("Friends");
category.sendKeys("Coworkers");
category.sendKeys("Businesses");
category.sendKeys("Family");
I tried to make category.sendKeys(""); once and it works well.
But throws this: "stale element reference: element is not attached to the page document" when i get a lot. How i can change this elements one by one?
This is kinda a strange one. The DOM keeps changing which makes it harder to see what's going on so that you can do the right thing to make it work. You have to click one element which changes the DOM and inserts an INPUT which is what you need to .sendKeys() to. I have tested the code below and it works.
I like to create functions for things like this so that they are reusable. This function changes the first name. rowIndex is the row of the table you want to change and firstName is the desired first name. You have to wait for the table to finish loading because it loads dynamically after the page is loaded.
public static void setFirstName(int rowIndex, String firstName)
{
WebElement firstNameElement = new WebDriverWait(driver, 10)
.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("tr[__gwt_row='" + rowIndex + "'] > td > div")))
.get(1);
firstNameElement.click();
firstNameElement.findElement(By.tagName("input")).sendKeys(firstName + "\n");
}
To change the first name of the first row to "FirstName" you would call it like,
setFirstName(0, "FirstName");

First character is missing inconstantly while sending string to the ExtJS input via sendKeys()

I randomly face the issue of missing first character in the ExtJS5 input field, while sending string via sendKeys method.
System info:
Ubuntu 14.04 -> docker containers with selenium grid (2.48.2)
Browser Firefox
Code is simple. I just get input web element, wait if it's clickable (i.e. isEnabled and isDisplayed), clear and send string:
wait.until(ExpectedConditions.elementToBeClickable(input)).clear();
input.sendKeys(value);
input element is simple too:
<input id="textfield-1455-inputEl" data-ref="inputEl" type="text" role="textbox" size="1" name="name" class="x-form-field x-form-required-field x-form-text x-form-text-default x-form-focus x-field-form-focus x-field-default-form-focus" autocomplete="off" componentid="textfield-1455"/>
I've noticed that issue occurs only for the first sendKeys() executing on the page:
Enter the page, wait for page load, work with first input
Enter the page, wait for page load, choose Enable into corresponding select box in order to enable input field, work with input field (image with this example is attached)
Enter the page, wait for page load, click button add in order to add the needed input field, work with input field
Other occurrences of the sendKeys on the page are stable.
I've looked for similar questions. It does not seem the issue with special characters (Missing characters example: 46-> 6; coverTest -> overTest; 1 -> nothing);
Also, I don't think it's an issue with missing characters due to remote webdriver infrastructure. The tests fail randomly but in exact places.
I know that I can use sendKeys(), then check the value of the input and repeat the sending action. However, it's the last option.
Is there any additional check needed for ExtJS input (any attribute in DOM) in order to be sure that input field is ready?
Appreciate your help.
Some times it happens with me. Try clicking on to the field first, but it's a wild guess assuming there can be some focus related issues.
Your sequence could be somewhat like this:
wait.until(ExpectedConditions.elementToBeClickable(input)).click();
input.clear();
input.sendKeys(value);
Weird thing is that I actually faced a situation, where I clicked it twice before sending values and it worked somehow :P
Another thing to try could be using a non-native javascript executor.
JavascriptExecutor myExecutor = ((JavascriptExecutor) driver);
myExecutor.executeScript("arguments[0].value='6';", input);
Sorry man, if the system would have been in front of me I'd have tried much more things.
I was struggling with sendKeys failing my self, but the following works pretty consistently. The method findVisibleElement is a custom wrapper for driver.until....
protected static boolean sendKeysByChar(By by, String input)
{
WebElement field = driver.findVisibleElement(by).base();
field.click();
field.clear();
for (int i = 0; i < input.length(); i++) {
String current = driver.findElement(by).getAttribute("value");
String nextChar = String.valueOf(input.charAt(i));
while (current.length() <= i || !current.endsWith(nextChar)) {
field.sendKeys(nextChar);
current = driver.findElement(by).getAttribute("value");
}
}
field = driver.findElement(by); // Refresh element
if (field.getAttribute("value").equals(input)) { return true; }
log.warn("Send keys by char failed.");
return false;
}