Selenium - Java - How to check button is enabled or not? - selenium

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 :)

Related

Selenium java: How to fail test if element not present?

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();
}

How can I check if element is present in laravel dusk test?

In the below code, I want to check if the element is present at XPath, then only it should execute code.
if($browser->driver->findElement(WebDriverBy::xpath('/html/body/div[1]/div/section/div[3]/div[2]/div/table/tbody/tr['.$i.']/td[2]'))!==null)
{
$sort=$browser->driver->findElement(WebDriverBy::xpath('/html/body/div[1]/div/section/div[3]/div22]/div/table/tbody/tr['.$i.']/td[2]'))->gettext();
echo $sort;
}
Or else please suggest if there is another way to check element is present in laravel dusk.
P.S. I tried whenAvailable method but it couldn't help me in this case.
Found another better and workable solution:
if ($browser->element('#IDString')) {
}
Laravel-Dusk provides two straight-forward method assertVisible (5.4+) and assertPresent (5.6+).
assertVisible makes sure the element is in the visible view-port of the web-page.
assertPresent makes sure the element exists in the source code of the page.
You can pass in any html selector to check if the element if visible.
/** #test */
public function assert_that_home_page_opens_up(){
$this->browse(function ($browser) {
$browser->visit('/')
->assertPresent('#my-wrapper')
->assertVisible('.my-class-element')
});
}
xpath
The above methods can only be used if you have a selector (class or id) for the element that you are looking for.
If you need to check if an element exists at a particular xPath, you can make use of driver instance on $browser object, to directly call the methods provided by Facebook Web-driver API:
$this->assertTrue(
count(
$browser->driver->findElements(WebDriverBy::xpath('//*[#id="home-wrapper"]'))
) > 0);
Source : https://www.5balloons.info/how-to-check-if-element-is-present-on-page-using-laravel-dusk/
/*
* check element exist
* if it doesn't not exist
* will throw exception
*
* #retuen void
*/
try {
$this->browse(function (Browser $browser) {
$elementExist = $this->assertNotNull($browser->element('#idString'));
if (empty($elementExist)) {
\Log::info('element exist')
}
}
}
catch (\Exception $e) {
\Log::info($e->getMessage());
}
When I want to check to see if an element exists, I usually do something like this:
$this->browse(function (Browser $browser) {
$this->assertNotNull($browser->element('#idString'));
}

I wrote a function for window handling but it's not working in selenium webdriver

I am working on Selenium webdriver and I have write a function for window handling. I have written code for naukri.com popup handling. My scenario is to Open the naukri.com and without closing popup window. I want to switch main window and click on Login button.I have written the code and created a function. when I am running the script focus is going on main page and url is displayed as selected but I am not able to click on Login button. I am not understanding where the problem is.Please suggest me.
public static WebDriver fn_SetFocus_According_Title(WebDriver dObj, String arg_title)
{
Set<String> setcol_windowHandle=dObj.getWindowHandles();
Iterator<String>itcol_handleval=setcol_windowHandle.iterator();
while(itcol_handleval.hasNext()==true){
String windowhanldval=itcol_handleval.next();
dObj=dObj.switchTo().window(windowhanldval);
String apptitle=dObj.getTitle();
if(apptitle.contains(arg_title))
{
dObj=dObj.switchTo().window(arg_title);
}
}
return dObj;
}
}
WebDriver dObj = new FirefoxDriver();
dObj.manage().window().maximize();
dObj.get("https://www.naukri.com");
dObj.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
dObj=fn_SetFocus_According_Title(dObj,"Jobs - Recruitment - Job Search - Employment - Job Vacancies - Naukri.com");
dObj.findElement(By.xpath("//a[#id='login_Layer']")).click();
Make the following changes in your code:
Change to:
dObj.switchTo().window(windowhanldval);
Reduce the actual string of "arg_title" as you would be looking for this entire string within the String obtained by getTitle()
When you are already on that page trying to match the page title which means the focus is already on the actual page where we need to locate the Login button element. So remove the second switch () line entirely. Rather use "break" to come out if loop.
Let me know if these steps works for you.
The function below works for me.
public static void switchToWindow(String windowTitle)
{
for (String window : driver.getWindowHandles())
{
driver.switchTo().window(window);
if (driver.getTitle().equals(windowTitle))
{
return;
}
}
throw new InvalidParameterException("The window titled <" + windowTitle + "> does not exist.");
}
One issue you may run into is that when a new tab/window is created, you may need to wait for it to appear. To do that, you can use something like
int count = driver.getWindowHandles().size() + 1; // add 1 to the current window count
// do something that spawns a new window
new WebDriverWait(driver, 3).until(ExpectedConditions.numberOfWindowsToBe(count));
You don't need to return the WebDriver instance. It's the same driver instance you are already using. If the expected window title is not found, the function will throw an exception.
Hope this will work for you.
public void Parenthandle(WebDriver wb){
try {
String ParentPageHandle = wb.getWindowHandle();
for (String newPage : wb.getWindowHandles()) {
if (!ParentPageHandle.equals(newPage)) {
wb.switchTo().window(newPage);
}
}
} catch (Exception e) {
System.err.println(e.getMessage());
}

What is the correct Selenium syntax to assert that I'm unable to view a particular link/element?

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.

Check if a WebElement is stale without handling an exception

I'm currently checking to see if a WebElement is stale by doing the following:
public static boolean isStale(WebElement element) {
try {
element.click();
return false;
} catch (StaleElementReferenceException sere) {
return true;
}
}
This is the same as the solution offered to this question:
Check for a stale element using selenium 2?
However, this seems rather messy to me. Is there a cleaner way that I can check if an element is stale, without having to throw and catch an exception?
(Also, as a side, if I have to stick with throwing and catching an exception, is there something better to do than clicking/sending keys/hovering to throw said exception? I might have a WebElement that I don't want to do any of these actions on, as it may inadvertently affect something else.)
Webdriver itself uses the try/catch-construction to check for staleness as well.
from org.openqa.selenium.support.ui.ExpectedConditions.java:
public static ExpectedCondition<Boolean> stalenessOf(final WebElement element) {
return new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver ignored) {
try {
// Calling any method forces a staleness check
element.isEnabled();
return false;
} catch (StaleElementReferenceException expected) {
return true;
}
}
#Override
public String toString() {
return String.format("element (%s) to become stale", element);
}
};
}
The isEnabled() check is better than using a click action - clicking an element might cause unwanted side effects, and you just want to check the element's state.
I know this already has an accepted answer and I don't know the bigger context of how you use the staleness check but maybe this will help you or others. You can have ExpectedConditions.stalenessOf(WebElement) do the work for you. For example,
WebElement pageElement = driver.findElement(By.id("someId"));
WebDriverWait wait = new WebDriverWait(webDriver, 10);
// do something that changes state of pageElement
wait.until(ExpectedConditions.stalenessOf(pageElement));
In this case, you don't have to do pageElement.click(), etc. to trigger the check.
From the docs, .stalenessOf() waits until an element is no longer attached to the DOM.
References: ExpectedConditions
Classic statement for C# to check staleness of web element
protected bool IsStale
{
get { return ExpectedConditions.StalenessOf(webElement)(WebDriver); }
}
I don't fully understand what you want to do. What do you mean by 'messy' solution?
Maybe you can use an explicite wait an as expected condition stalenessOf in combination with not.
But every solution with that don't seems stable to me.
What I do is, that I have an clicking routine in a helperclass, the idea is like:
public void ClickHelper(WebDriver driver, By by){
int counter = 1;
int max = 5;
while (counter <= max) {
try {
WebElement clickableWebElement = driver.findElement(by);
clickableWebElement.click();
return;
} catch (StaleElementReferenceException e) {
System.out.print("\nTry " + counter + " with StaleElementReferenceException:\n" + e.getMessage() + "\n");
}
versuche++;
}
throw new RuntimeException("We tried " + max + " times, but there is still an Exception. Check Log!");
}
Be careful, I just entered this by simplyfying my own methode (there are some more checks and personally I use xpath and not by etc). There might be some typo-mistakes, but i guess you will understand the basic idea. Since I use this Helpermethode, I don't have to care about Staleness of webelements. You can alter the max-value, but personally I think, if the website is such unstable, that the Element is stale so much, I would talk to the developer, because this would not be a good website.
This should work without dependency of display/ enabled:
def is_element_on_page(element):
try:
element.get_attribute('')
return True
except StaleElementReferenceException:
return False