Starting with Selenium/Cucumber, I want to check the presence of an element on my application (h1 title).
For this I drew inspiration from the following code when writing this method:
#Then("the admin arrives on the clients/prospects dashboard")
public boolean the_admin_arrives_on_the_clients_prospects_dashboard() {
return driver.findElements(By.xpath("//h1[contains(text(), 'Dashboard')]")).size() != 0;
}
However, I would like my test to fail if the element is not present. Is the fact that the method returns the "false" value enough to make the test fail? Many thanks
list.size() != 0 returning false indicates the list doesn't contain any elements.
That definately validates the element is not present.
With the help of Michael Mintz, here's how you do asserts in Cucumber.
NOTE: You need to import Junit.Assert in your Step Definition file.
#Then("the admin arrives on the clients/prospects dashboard")
public boolean the_admin_arrives_on_the_clients_prospects_dashboard() {
assertFalse(driver.findElements(By.xpath("//h1[contains(text(), 'Dashboard')]")).size() != 0);
}
You can check use isEmpty() method for your check:
public boolean isElementPresented(final By locator) {
return webDriver.findElements(locator).isEmpty();
}
Related
I have tried so many times isenabled property but it always return "true" as the button is disabled on the page but it still return "True"
Please suggest the workaround to handle this?
Here is the code:
public void OpenSearchPage_and_verifyaddtofavoriteslink() throws InterruptedException
{
try
{
driver.navigate().to(favouritepagelink);
driver.findElement(FavoritesCheckBoxSelectAll).click();
//verify condition if product exist on favorites page
if(driver.findElement(FavoritesDelConditionCheck).isEnabled())
{
System.out.println("Enter in condition");
}
else
{
System.out.println("Out of condition");
}
}
catch(Exception ex)
{
System.out.println("SearchPage not opened: " +ex.getMessage());
}
}
Suggestions:
There can two reasons for getting this issue:
i) Issue with object
ii) Issue with the property
I) Issue with object: We can ensure we are using the right object for the button
and refresh the object before performing the operation
ii) Issue with property: Please check if some other property other then enabled is indicating this behaviour by verifying the html code behaviour.
Problem resolved :)
I have used getattribute to get class name then apply condition based on class attribute and its working fine.
Thank you all for the help :)
I need to wait for all elements to not be visible with an attribute 'id' that contains the word 'mask'. I have tried like this:
//*[contains(#id *= 'mask')]
However it is giving me an element not found exception.
I believe the syntax you're looking for is:
//*[contains(#id,'mask')]
I do something similar where I wait until the count is zero for classes that contain "BlockUI":
public static void waitForBlockUIToDisappear() {
// This function checks the entire currently-loaded web page for the
// presence of any web element of the
// class "blockUI" and loops until there are none. The presence of an
// element with this class does exactly
// what it implies: it blocks user input. If you get the error that a
// different web element would receive
// the click, for example, this is why and you'd need to call this
// method before doing a click. Generally,
// this function should be implemented before sending any input to a web
// page - click, sendkeys, select...
String blockUI = "//*[contains(#class,'blockUI')]";
while (true) {
if (driver.findElements(By.xpath(blockUI)).size() == 0)
break;
}
;
}
You should be able to alter that code to look for your id to contain your text.
You can use explicit wait in this case, as below.
WebDriverWait wait = new WebDriverWait(driver,15);
wait.until(ExpectedConditions.invisibilityOfAllElements(driver.findElements(By.xpath("//*[starts-with(#id,'mask')]"))));
In c# they were not implemented this method, but you can implement that.
Below is the url that can help you to write.
https://github.com/SeleniumHQ/selenium/blob/master/dotnet/src/support/UI/ExpectedConditions.cs#L140
I have a Selenium test that is supposed to verify that I'm unable to see a button link unless there is a certain amount of information present on a page such as a pagination link for example. Here is my Selenium assert statement:
def test_bottom_links
load_page('orgs/apache_software')
$driver.find_element(:xpath => "//a[#id='btn_orgs_see_all_projects']").element? == false
end
In my mind this makes sense to me but I receive this error when I run my test:
Selenium::WebDriver::Error::NoSuchElementError: Unable to locate element: {"method":"xpath","selector":"//a[#id='btn_orgs_see_all_projects']"}
The above error is what I want as a passing statement. I don't want Selenium to find this element because it should not be there.
I've also tried this and I get the same error:
$driver.find_element(:xpath => "//a[#id='btn_orgs_see_all_projects']").displayed? == false
I was wondering what the correct syntax should be to make this test pass. I've referred to these linksassertNotSomething and List of Selenium Methods. However, these don't have examples of how they are used so I was wondering how someone would write a test like the above. Thanks for any help offered.
Here's a simple boolean check method that should work.
boolean checkForElementPresence(By locator)
{
try {
driver.findElement(locator);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
You can switch to $driver.find_elements that will return an array without raising an exception. Then you can check for the size of the array to make sure it is empty indicating that the element was not found.
I am using selenium to perform repetitive tasks on a website - a very useful feature for automating web tasks.
I am stuck on how to perform an action only if certain text is present on the page. Is this possible?
I do not want the lack of text to break the test case - only to bypass the action.
I have the Flow Control plugin too, but havent figured out how to make this do any more.
In Java you can make a method that returns true or false whether an element is present or not :
public boolean isElementPresent(By by) {
try {
return driver.findElement(by) != null;
} catch (NoSuchElementException e) {
return false;
}
}
And concerning the text you want to find you can do :
if(isElementPresent(By.xpath("//*[contains(text(),'Some text')]"))){
// Do your tests here
}
How are you finding out if jqGrid is loaded and ready to be used, via selenium.
Some details :
Im using C# driver
I have a method : new WebDriverWait(driver, new TimeSpan(0, 0, 0, 30)).Until(x => loadingdissapearedcondition) which im using to wait until Loading.. element is gone.
I also sometimes use this script :
private const string script = #"return ($('#{0}').jqGrid('getGridParam', 'reccount') !=x undefined) && ($('#{0}').jqGrid('getGridParam', 'reccount') != 0) && (!$('#load_{0}').is(':visible')) && (!$('#busyIcon').is(':visible'))";
private readonly string waitScript;
waitScript = string.Format(script, jqGridId);
public void WaitUntilLoadIconDissappears()
{
driver.WaitUntil(MAXWAIT, Wait);
}
public bool Wait()
{
var executeScript = ((IJavaScriptExecutor) driver).ExecuteScript(waitScript);
bool result;
bool tryParse = bool.TryParse(executeScript.SafeToString(), out result);
return tryParse && result;
}
to find if jqGrid has records and loading done.
I require something better - as even the above two does not make driver wait until load finishes, if we are using local data for jqGrid. Im also curious what is the best way, or at the minimum, how others are dealing with this problem.
I never used Selenium before, so I'm not sure that I understood your problem correctly. jqGrid will be first initialized and then (optionally) the data can be loaded from the server. During the initializing stage the original <table id="grid"></table> element will be converted to relatively complex HTML fragment which is the grid. At the end of the initialization the DOM element of the table (the $("#grid")[0]) will get the expando grid.
So you can use the test like
if ($("#grid")[0].grid) {
// grid is initialized
}
to determine that the grid is already initialized. jqGrid uses the same test internally (see here for example).
Here is solution for Java and jqgrid.
If grid data is not loaded yet then right pager has no value, so simply check its length. Methods such as isElementPresent, isDisplayed etc. seems not to work for grid right pager object. It's always present in page code while ajax, but text value is set when dynamic data is loaded.
public void waitForGridPagerRight(String gridName) throws Exception {
for (int second = 0;; second++) {
if (second >= 15) {
fail("Timeout.");
}
try {
if (driver
.findElement(By.id("pager_" + gridName + "_right"))
.getText().length() > 2)
break;
} catch (Exception e) {
}
Thread.sleep(1000);
}
}
Not sure why #Oleg's answer didn't work for me. It seemed like grid was being populated even before the ajax call was being made. It appears there's some change in newer versions maybe. It look like the last thing to happen in the ajax call is that the "loading" block is hidden, so instead I find that element and check it's display attribute a la:
def wait_for_jqgrid(self, t=20):
def check_jqgrid(driver):
#the last thing jqgrid does after the ajax call is to turn off the loading div
#so we find it and check to see if its display attribute is no longer set to 'none'
script = 'pid = $.jgrid.jqID($(".ui-jqgrid-btable").get(0).p.id); return $("#load_"+pid).get(0).style.display == "none";'
return driver.execute_script(script)
WebDriverWait(self.driver, t).until(check_jqgrid)
When the loading div is hidden, we are done. This is python but the same javascript bit should work in Java or whatever.