Geb: Check if an element is not present/displayed - geb

I want to check that a particular element is not displayed in Geb.
selectedClients { $(".selection") }
Here are several of the stuff I've tried so far: none working.
assertThat(module.selectedClients.not.displayed)
assertThat(module.selectedClients.displayed).isEqualTo(false)
Thanks in advance!
EDIT
To clear the ambiguity, what I was actually checking for here was the presence of child elements within the object. I was able to resolve this, using a size() check.
assertThat(module.selectedClients.size()).isEqualTo("0")

assertThat(!module.selectedClients.displayed)

Try iterating through each element and checking visibility
module.selectedClients.each {
assertThat(it.displayed).isEqualTo(false)
}
I'm not too familiar with junit syntax :/

Simply do this:
if(elementName.size() ==1) or not.

Related

How to check input span styled as checkbox is selected using Selenium? Only :: after as the difference between states

I am trying to check whether a checkbox is selected. My checkbox is styled using input and span, not using the checkbox tag. As it's not a default checkbox I can't use methods such as isSelected or isChecked to check its state. I was then trying to check if any class belongs to a state but not the other. However, the only difference I've found so far is that when the element is selected an ::after appears but not sure how to go about checking this?
I found a tutorial with a similar issue, but don't know much about Javascript and not sure how to adapt it to my case.
https://www.quora.com/How-do-I-locate-After-and-Before-css-tag-in-selenium-webdriver
Before clicked
After clicked
That's what is being used and as per #pguardiario answer
System.out.println(js.executeScript("return window.getComputedStyle(document.querySelector('.custom-checkmark'), ':after').getPropertyValue('content')"));
But both when it's selected or not it returns the same output (empty string)
UPDATE
Found the difference between the selected and unselected states. The .custom-checkmark:after style has display-none when the checkbox is not selected.
Not sure still how to use this info as that's what I have at moment and they return display none both before and after the checkbox is clicked.
#Test
public void testingCheckbox() {
JavascriptExecutor js = (JavascriptExecutor) wd;
System.out.println(js.executeScript("return window.getComputedStyle(document.querySelector('.custom-checkmark'), ':after').getPropertyValue('display')"));
lp.clickCheckBox();
System.out.println(js.executeScript("return window.getComputedStyle(document.querySelector('.custom-checkmark'), ':after').getPropertyValue('display')"));
}
NEW FINDING
It seems there's actually 'two checkboxes'. One with the span tag and the other one with the span. They appear together when unselecting some attributes.
Thanks for the help.
I can't test it but it should look something like this:
driver.executeScript('return window.getComputedStyle(document.querySelector(".custom-checkmark"), ":after").getPropertyValue("content")')
Sorry about the long line btw, Java doesn't have heredocs which makes this painful :(
Try use JavascriptExecutor, import them :
import org.openqa.selenium.JavascriptExecutor;
Try this :
WebElement chk = driver.findElement(By.xpath("//*[#class='custom-checkmark' and ./preceding-sibling::*[#id='terms_checkbox']]"));//or you have
String getPro;
getPro = ((JavascriptExecutor)driver).executeScript("return window.getComputedStyle(arguments[0], ':after').getPropertyValue('background-color');",chk).toString();
System.out.println(getPro);
chk.click();
Thread.sleep(1000);
getPro = ((JavascriptExecutor)driver).executeScript("return window.getComputedStyle(arguments[0], ':after').getPropertyValue('background-color');",chk).toString();
System.out.println(getPro);
Not sure with .getPropertyValue('background-color'), but this may be a clue.
Try the below CSS selectors for identifying that
span.custom-checkmark:after
And also please see the below link for more details
Extracting content in :after using XPath
Got the code to work. Targeting the input tag instead of span solved the problem. I had a mistake on my code when tried that first time so that's why though the isSelected field wasn't working and moved on to target the span tag instead which opened this thread here. Sorry about that and thanks for everybody's help.

How to write xpath for the on/off button present in a table for which class is compound class

This element can be turned off or on. As the class is compound class, not sure how to write the xpath. So wrote like this
//tr[1]/td[4]/div[1]/div/div/div[#css='div.ios-switch.on']
Screen shots are attached here
Can you help me in writing the xpath for this element
Use this instead - //tr[1]/td[4]/div[1]/div/div/div[#class='ios-switch on']
"#checkbox1011 [class^='ios-switch']"
or
"#checkbox1011 .ios-switch.on,.ios-switch.off"
Try using these CSS selectors.
//div[#id='checkbox1011']//td[#class='ios-switch-on']
Try:
//tr[1]/td[4]/div[1]/div/div/div[#css='.ios-switch.on' or '.ios-switch.off']
Hopefully this should work.
For the above screenshot, let me assume the username as sabrina galloway.
The toggle switch should present in the same row of username column.
You can use xpath like,
.//tr[./descendant::td[contains(.,'sabrina galloy')]/descendant::*[contains(#class,'ios-switch')]/div[#class='handle']
Use //div[starts-with(#class,'ios-switch')]

Selenium Webdriver - using isDisplayed() in If statement is not working

I am creating a script that involved searching for a record and then updating the record. On the search screen, the user has the option of viewing advanced search options. To toggle showing or hiding advanced search is controlled by one button.
<a title="Searches" href="javascript:expandFilters()"><img border="0" align="absmiddle" alt="Advanced" src="****MASKED URL****"></a>
The only difference between the properties of the search button when it is showing or hiding the advanced search is the img src:
When advanced search is hidden the IMG src ends with "/Styles/_Images/advanced_button.jpg", when advanced search is visible, the IMG src ends with "/Styles/_Images/basic_button.png"
When I open the page, sometimes the Advanced search options are showing, sometimes they aren't. The value that I want to search on appears in the Advanced section, so for my script to work I have added an IF statement.
<input type="text" value="" maxlength="30" size="30" name="guiSystemID">
The IF statement looks for the fields that I need to enter data into, and if the field does not exist then that would indicate that the Advanced options are not visible I need to click on the button to expand the search option.
I created the following IF statement.
if (!driver.findElement(By.name("guiSystemID")).isDisplayed()) {
driver.findElement(By.cssSelector("img[alt='Advanced']")).click();
}
When I run the script and the Advanced search is expanded then the script runs successfully. However, when I run the script and the Advanced search is not expanded, the script fails, advising me that it could not find the object "guiSystemID". This is frustrating because if it can't find it then I want the script to continue, entering into the True path of the IF statement.
Has anyone got any suggestions about how else I could assess if the field is appearing without having the script fail because it can't find the field.
Thanks in advance
Simon
I might be late in answering this, but it might help someone else looking for the same.
I recently faced a similar problem while working with isDisplayed(). My code was something like this
if(driver.findElement(By.xpath(noRecordId)).isDisplayed() )
{
/**Do this*/
}
else
{
/**Do this*/
}
This code works pretty well when the element that isDisplayed is trying to find is present. But when the element is absent, it continues looking for that and hence throws an exception "NosuchElementFound". So there was no way that I could test the else part.
I figured out a way to work with this(Surround the {if, else} with try and catch block, say something like this.
public void deleteSubVar() throws Exception
{
try
{
if(driver.findElement(By.xpath(noRecordId)).isDisplayed() )
{
/**when the element is found do this*/
}
}
catch(Exception e)
{
/**include the else part here*/
}
}
Hope this helps :)
I've had mixed results with .isDisplayed() in the past. Since there are various methods to hide an element on the DOM, I think it boils down to a flexibility issue with isDisplayed(). I tend to come up with my own solutions to this. I'll share a couple things I do, then make a recommendation for your scenario.
Unless I have something very specific, I tend to use a wrapper method that performs a number of checks for visibility. Here's the concept, I'll leave the actual implementation approach to you. For general examples here, just assume "locator" is your chosen method of location (CSS, XPath, Name, ID, etc).
The first, and easiest check to make is to see if the element is even present on the DOM. If it's not present, it certainly isn't visible.
boolean isPresent = driver.findElements(locator).size() > 0;
Then, if that returns true, I'll check the dimensions of the element:
Dimension d = driver.findElement(locator).getSize();
boolean isVisible = (d.getHeight() > 0 && d.getWidth() > 0);
Now, dimensions, at times, can return a false positive if the element does in fact have height and width greater than zero, but, for example, another element covers the target element, making it appear hidden on the page (at least, I've encountered this a few times in the past). So, as a final check (if the dimension check returns true), I look at the style attribute of the element (if one has been defined) and set the value of a boolean accordingly:
String elementStyle = driver.findElement(locator).getAttribute("style");
boolean isVisible = !(elementStyle.equals("display: none;") || elementStyle.equals("visibility: hidden;"));
These work for a majority of element visibility scenarios I encounter, but there are times where your front end dev does something different that needs to be handled on it's own.
An easy scenario is when there's a CSS class that defines element visibility. It could be named anything, so let's assume "hidden" to be what we need to look for. In this case, a simple check of the 'class' attribute should yield suitable results (if any of the above approaches fail to do so):
boolean isHidden = driver.findElement(locator).getAttribute("class").contains("hidden");
Now, for your particular situation, based on the information you've given above, I'd recommend setting a boolean value based on evaluation of the "src" attribute. This would be a similar approach to the CSS class check just above, but used in a slightly different context, since we know exactly what attribute changes between the two states. Note that this would only work in this fashion if there are two states of the element (Advanced and Basic, as you've noted). If there are more states, I'd look into setting an enum value or something of the like. So, assuming the element represents either Advanced or Basic:
boolean isAdvanced = driver.findElement(locator).getAttribute("src").contains("advanced_button.jpg");
From any of these approaches, once you have your boolean value, you can begin your if/then logic accordingly.
My apologies for being long winded with this, but hopefully it helps get you on the right path.
Use of Try Catch defies the very purpose of isdisplayed() used as If condition, one can write below code without using "if"
try{
driver.findElement(By.xpath(noRecordId)).isDisplayed();
//Put then statements here
}
Catch(Exception e)
{//put else statement here.}

Xpath for href element

I need to click on the below href element,which is present among similar href elements.
<a id="oldcontent" href="listDetails.do?camp=1865"><u>Re-Call</u></a>
Can anyone provide me xpath to click the above href link?
Try below locator.
selenium.click("css=a[href*='listDetails.do'][id='oldcontent']");
or
selenium.click("xpath=//a[contains(#href,'listDetails.do') and #id='oldcontent']");
This works properly try this code-
selenium.click("xpath=//a[contains(#href,'listDetails.do') and #id='oldcontent']");
This will get you the generic link:
selenium.FindElement(By.XPath("xpath=//a[contains(#href,'listDetails.do')")).Click();
If you want to have it specify a parameter then you will have to test for each one:
...
int i = 1;
selenium.FindElement(By.XPath("xpath=//a[contains(#href,'listDetails.do?camp=" + i.ToString() + "')")).Click();
...
The above could utilize a for loop which navigates to and from each camp numbers' page, which could verify a static list of camps.
Please excuse if the code is not perfect, I have not tested myself.
have you tried:
//a[#id='oldcontent']/u[text()='Re-Call']
for me worked //a[text()='Re-Call']
what worked for me:
//a[contains(#href,'logout')]
Below works fine.
//a[#id='oldcontent']
If you've tried certain ones and they haven't worked, then let us know, otherwise something simple like this should work.
Best way to locate anchor elements is to use link=Re-Call:
selenium.click("link=Re-Call");
It will work..

Finding text on page with Selenium 2

How can I check whether a given text string is present on the current page using Selenium?
The code is this:
def elem = driver.findElement(By.xpath("//*[contains(.,'search_text')]"));
if (elem == null) println("The text is not found on the page!");
If your searching the whole page for some text , then providing an xpath or selector to find an element is not necessary. The following code might help..
Assert.assertEquals(driver.getPageSource().contains("text_to_search"), true);
For some reason, certain elements don't seem to respond to the "generic" search listed in the other answer. At least not in Selenium2library under Robot Framework which is where I needed this incantation to find the particular element:
xpath=//script[contains(#src, 'super-sekret-url.example.com')]
A simpler (but probably less efficient) alternative to XPaths is to just get all the visible text in the page body like so:
def pageText = browser.findElement(By.tagName("body")).getText();
Then if you're using JUnit or something, you can use an assertion to check that the string you are searching for is contained in it.
assertThat("Text not found on page", pageText, containsString(searchText));
Using an XPath is perhaps more efficient, but this way is simpler to understand for those unfamiliar with it. Also, an AssertionError generated by assertThat will include the text that does exist on the page, which may be desirable for debugging as anybody looking at the logs can clearly see what text is on the page if what we are looking for isn't.