How to select an element in ng-autocomplete in protractor? - angularjs

Passing text through
sendKeys("dublin,south Africa");
It is unable to select the first element in autocomplete.

issue resolved.
this.checkin = function(text,index){
element( by.css('[ng-click="showMapTextBox2()"]') ).click();
// element(by.model("location")).sendKeys(text);
browser.actions()
.mouseMove(element(by.model("location"))
.sendKeys(text))
.perform().then(function(){
browser.sleep(500);
// press the down arrow for the autocomplete item we want to choose
for(i = 0; i < index ; i++){
browser.actions().sendKeys(protractor.Key.ARROW_DOWN).perform();
}
browser.sleep(500);
browser.actions().sendKeys(protractor.Key.ENTER).perform();
});
browser.sleep(3000);
};
spec_test code:
post_text.checkin("new Delhi, India",1);

Manually type what you want the test to perform and inspect the element of the autocomplete. You'll use protractor.ExpectedConditions to wait for that element then click on it after you send keys.

You need to do 2 things:
Enter text. Sometimes it is needed to press Tab to force the autocomplete to display options
Select appropriate drop down option
Example code in C#:
fieldElement.ClearAndSendKeys(partialValue);
fieldElement.SendKeys(Keys.Tab);
GetFieldDropdown(completeValue).Click();
GetFielDropdown() method details depending on your DOM. Here is a simplified example from a project I'm working on:
private IWebElement GetFieldDropdown(string dropdownValue)
{
return FindElement(By.XPath($"//span[contains(.,'{dropdownValue}')]"));
}
Note that if there is a delay in autocomplete being displayed above code won't work unchanged (The FindElement will not return an element). You'll need to wait for the dropdown option to be displayed before clicking on it.
PS - partialValue and completeValue can be the same

Related

Checkbox is Selected but can't able to clicked on it using selenium

On clicking a checkbox, the checkbox is highlighted but its not clicked
and i don't get exception .
<input name="include_notice" onclick="javascript:TogglePublishDates();" type="checkbox">
I identify this checkbox with Name and tried using sendkeysReturn and sendKeysEnter.
Note: This test case was running good for quite a long time.No changes were made in Selenium Web driver or Firefox.
You can try to click using java script, as shown below:
JavascriptExecutor e = (JavascriptExecutor)wd;
e.executeScript("arguments[0].click();", driver.findElement(By.name("include_notice")));
If you still observe the inconsistent behavior, you may want to implement the retry mechanism, as shown below:
//1) Finding the check box
WebElement checkBox = driver.findElement(By.name("include_notice"));
//2) Checking whether check box is already checked
if (!checkBox.isSelected()) {
JavascriptExecutor e = (JavascriptExecutor)wd;
e.executeScript("arguments[0].click();", checkBox);
//3) Checking whether first attempt to check the check box worked
if (!checkBox.isSelected()) {
//4) Retrying
checkBox.click();
}
}
Let me know, if you have any further queries.
You can try with these below codes:
driver.findElement(By.name("include_notice")).click(); //find checkbox element and click on it.
Click checkbox using java-script executor.
WebElement checkbox = driver.findElement(By.name("include_notice"));
((JavascriptExecutor) driver).executeScript("arguments[0].click();", checkbox);
If Checkbox is already selected then use this code.
WebElement checkbox = driver.findElement(By.name("include_notice"));
if (!checkBox.isSelected()) //checkbox is not selected then only it will select the checkbox.
{
checkBox.click();
System.out.println(checkbox.isSelected());
}

Can't select an md-select dropdown option using Selenium

I have an angular-material dropdown with a set of options, and am attempting to select one of the options. I'm selecting them as follows:
html file:
<md-select name="myDropdown"
ng-model="addCompany.details.someModel"
ng-change="addCompany.swapDisplayedAreas()"
required>
<md-option value="Company A">Company A</md-option>
<md-option value="Company B">Company B</md-option>
</md-select>
python test:
input = self.browser.find_element_by_name('myDropdown')
input.click()
choice = self.browser.find_element_by_xpath("//*[contains(text(), 'Company A')]")
choice.click()
However, no matter how I try to select the option, I either get the following error:
selenium.common.exceptions.WebDriverException: Message: Element is not
clickable at point (750, 423). Other element would receive the click:
<md-backdrop style="position: fixed;" class="md-select-backdrop
md-click-catcher ng-scope"></md-backdrop>
Or I can see that the element is clicked on, but that the dropdown still stays pulled out. Attempting to click on any other element on the page while the dropdown is still pulled out gives a similar md-backdrop would receive the click error.
Any idea how I can choose a dropdown selection for an md-select element? I've tried disabling md-backdrop for my input elements without any success.
You should try using WebDriverWait to wait until options open from the dropdown and getting visible and clickable before click as below :-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
#find dropdown and click to open options
input = self.browser.find_element_by_name('myDropdown')
input.click()
#now wait until options getting visible and clickable
choice = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "md-option[value = 'Company A']")))
choice.click()
I would guess the issue may be one of the following:
There is another element on the page with the text "Company A" and that element is trying to be clicked even though the dropdown option is clearly the element you want selenium to click. This is because selenium clicks the first element that satisfies the identifier. To check if this is the problem I would use the find elements and check how many elements are found. If that is the problem try using the css selectors such as value.
If you are using chrome I came across a similar problem with the chrome webdriver when testing an angular application.
This is the issue https://code.google.com/p/selenium/issues/detail?id=2766
I tried elegant workarounds but nothing worked...in the end I used the solution by Lukeis.
In java
int n=10;
String errorMessage;
for (int i=1; i<=n; i++)
{
try {
clickThis.click();
break;
} catch(WebDriverException driverException) {
Thread.sleep(1000);
errorMessage = driverException.toString();
}
if(i==n)
{
Assert.fail("Failed to click "+n+" times \n" + errorMessage);
}
}
It pretty much tries to click the element 10 times.

How to identify the webelements(button,drop down etc) by using selenium webdriver

How to identify webelement buttons by selenium webdriver
executeScript method is undefined. Where to add this
driver.executeScript("return $('body /deep/ <#selector>')") ?
Try below code for retrieving all dropdown values
WebDriverWait wait = new WebDriverWait(d, 10);
WebElement selectMonth = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[#title = 'Birthday']")));
selectMonth.click();
List<WebElement> allmonths = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.cssSelector("span#BirthMonth > div.goog-menu.goog-menu-vertical")));
for(WebElement month : allmonths) {
System.out.println(month.getText());
Hope it will help
We will get this type of Exception in below scenario.
If pages are not embedded in jQuery.
jQuery library is not loaded successfully.
Browser syn isssue.
First check pages is embedded in jQuery or not by executing below command on browser console
window.jQuery=='undefine' // Its for checking jQuery is present on page if yes then return true.
and
jQuery.active==0 // Its for checking jquery is activated on page if yes then return true.
then try below code
String getArgument="0"; // take single element
//String getArgument="";// take list of matched element
((JavascriptExecutor) driver).executeScript("return $( #selector).get(" + getArgument + ");");
You can simply identify element by using getTagName() as below :-
WebElement element = driver.findElement(By.id("countTd"));
// To verify if element is button
if(element.getTagName().equals("button")) {
element.click();
}
// To verify if element is dropdown
if(element.getTagName().equals("select")) {
// Now pass it to Select class to work
Select selectElement = new Select(element);
// Now you can get all options
List<WebElement> options = selectElement.getOptions();
//Now you can print all options text
for(WebElement option : options) {
System.out.println(option.getText());
}
}
Node :- There is no need to use JavascriptExecutor to perform click, it would be simply perform by calling .click() method.
Hope it helps..:)

Element is Not clickable at point(215, 251) error

I have a non-angular app where I click a link and a new popup modal appears. I then can select to upload a picture or video. I tell protractor and/or webdriver to click on the upload photos button.
If I use:
var addPhotos = element(by.css('#px-select-photo')).click();
I can visually see the button being pressed down however the test is then failed and the error not clickable at...(215, 251)
So then I thought I could trick it into clicking x y position (which I'm assuming those two numbers in the error are) and I get nothing
Code I used for that is:
browser.actions().mouseMove({
x: 702,
y: 621
}).click().perform();
It clicks, but not on the button.
Lastly I tried this:
var addPhotos = element(by.css('#px-select-photo'));
browser.executeScript('arguments[0].scrollIntoView()', addPhotos.getWebElement());
browser.actions().mouseMove(addPhotos).click().perform();
Which also yields no results.
Also, I am receiving this warning:
WARNING - more than one element found for locator By.cssSelector("#px-select-photo") - the first result will be used
However, there is only one element in the html file, don't know what thats all about either.
Please try below code:-
browser.executeScript('arguments[0].click()', addPhotos.getWebElement());
browser.actions().mouseMove(addPhotos).click().perform();
The warning might be the key to solving the problem.
Make your selector more specific and wait for the upload button to become clickable:
var EC = protractor.ExpectedConditions;
var addPhotos = element(by.css('#pxupload3 input#px-select-photo'));
browser.wait(EC.elementToBeClickable(addPhotos), 5000);
addPhotos.click();
Alternative option would be to get all elements by px-select-photo id and filter visible:
var addPhotos = element.all(by.css("#px-select-photo")).filter(function (addButton) {
return addButton.isDisplayed();
}).first();
addPhotos.click();

Selecting element from drop down list using selenium web driver

I want to select element from drop down list but in html they have used <img> tag. How can I achieve my goal?
This is stuff from my code:
public void country() {
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
Select country1 = new Select(country);
country1.selectByVisibleText("Canada");
}
I am getting this error while running testNg test
org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "img"
As you mentioned:
... but in html they have used <img> tag.
Which your error confirms. So, as per the error, you obviously cannot use Select().
You did not provide enough information to give a complete answer! But think about what the user would do. First they would click on the outer element:
driver.findElement(By.id(country)).click(); // replace country with appropriate ID, or other locator!
After this the user will have to wait for the menu to completely appear. Same for your code!
Next, the user can click on the desired option:
driver.findElement(By.id("Canada")).click(); // again, replace "Canada" with appropriate locator!
It is quite possible that the resulting menu will be long. Instead of the above .click() you may need to grab all the menu items based on some locator, and then iterate over all of them:
List<WebElement> items = driver.findElements(By....);
for(WebElement item : items) {
if(item.getText().equals("Canada"))
item.click();
}
Use the following code:
List<WebElement> lstOptions=Country1.getoptions();
for(WebElement lstOption:lstOptions){
if(lstOption.gettext().tolowercase().equals("canada"))
lstOption.click();
}
How to find dropdown list value.....
Use this code sure its help you!!!
driver.findElement(By.xpath("ur xpath")).click();
new Select(driver.findElement(By.name("EventType"))).selectByVisibleText("Birthday");
or
new Select(driver.findElement(By.id("city"))).selectByValue("Op3");

Resources