Caused by: org.openqa.selenium.NoSuchElementException: Element is not usable - selenium-webdriver

I use Selenium Webdriver + Thucydides. When I try to use a checkbox (any state: isEnabled(), isDisplayed(), isSelected()), so an error will occur. I tried the different locators: by id, name, xpath. The checkbox is available in the page source. All other element on the page work correctly. I use DisplayedElementLocatorFactory.
My locators:
#FindBy(id = "remember")
// #FindBy(xpath = ".//*[#type='checkbox']")
// #FindBy(name = "_remember_me")
protected WebElement rememberMeCheckbox;
HTML-source of checkbox:
<label for="remember" class="remember"><div class="checker" id="uniform-remember"><span><input type="checkbox" value="1" name="_remember_me" id="remember" /></span></div>Remember me</label>
My function:
public void isLoginFormLoadedCorrectly()
{
String pageSource = driver.getPageSource();
System.out.println(pageSource);
String errorMessage = "";
if (!loginInput.isDisplayed())
errorMessage += "Username field is not displayed or not found\r\n";
if (!passwordInput.isDisplayed())
errorMessage += "Password field is not displayed or not found\r\n";
if (!submitButton.isDisplayed())
errorMessage += "Submit button is not displayed or not found\r\n";
if (!passwordRecoveryLink.isDisplayed())
errorMessage += "Password recovery link is not displayed or not found\r\n";
if (!rememberMeCheckbox.isDisplayed())
errorMessage += "Remember me check-box is not displayed or not found\r\n";
// if (rememberMeCheckbox.isSelected())
// errorMessage += "Remember me check-box is selected\r\n";
assertThat(errorMessage, errorMessage.equals(""), is(true));
}
Error:
net.thucydides.core.webdriver.WebdriverAssertionError: org.openqa.selenium.NoSuchElementException: Timed out after 30 seconds. Unable to locate the element
Caused by: org.openqa.selenium.NoSuchElementException: Timed out after 30 seconds. Unable to locate the element
Caused by: org.openqa.selenium.NoSuchElementException: Element is not usable

I had the same error trying to click on the checkbox.
I solved it by clicking element with tag <span>, not <input>.
In your example it can be found, for instance, like this (element one level higher than your checkbox):
#FindBy(xpath = ".//*[#type='checkbox']/..")

I cannot reproduce your issue:
#RunWith(ThucydidesRunner.class)
public class VerificationTest {
#Managed
public WebDriver driver;
#ManagedPages
public Pages pages;
#Test
public void testCheckbox(){
CheckBoxPage pg = pages.get(CheckBoxPage.class);
pg.openAt("http://www.echoecho.com/htmlforms09.htm");
assertTrue("checkbox is displayed", pg.ckbxElement.isDisplayed());
assertTrue("checkbox is selected", pg.ckbxElement.isSelected());
}
}
where
public class CheckBoxPage extends PageObject{
#FindBy(css = ".table8 input:checked")
public WebElement ckbxElement;
public CheckBoxPage(WebDriver driver) {
super(driver);
}
}
with both FindBys: org.openqa.selenium.support.FindBy and net.thucydides.core.annotations.findby.FindBy
Since all other elements work make sure:
it's not in iframe.
htlm is correct

Related

Getting Error "Stale element reference: element is not attached to the page document" in selenium -Java

I have to iterate List through foreach loop and need to click on item. First item of the list is getting clicked but from second item onwards i am getting
org.openqa.selenium.StaleElementReferenceException: stale element
reference: element is not attached to the page document
public void checkFlightAvailabilityToSelectOutBound() throws InterruptedException {
boolean enabledFound=BookDateFlight();
System.out.println("checkFlightAvailabilityToSelectOutBound "+enabledFound);
if(enabledFound==false)
{
List<WebElement> nextAvailableDateList = driver
.findElements(By.xpath("somexpath"));
System.out.println("date list lenth "+nextAvailableDateList.size());
**for (WebElement nxtAvlDate : nextAvailableDateList)
{
try {
System.out.println("------"+nxtAvlDate);
System.out.println("Trying to click on the nxt avl date "+nxtAvlDate.getAttribute("id"));
//wait.until(ExpectedConditions.elementToBeClickable(nxtAvlDate));
//driver.navigate().refresh();
Thread.sleep(3000);
nxtAvlDate.click();
Thread.sleep(5000);**
//wait.until(ExpectedConditions.visibilityOfAllElements(flightInfoOutBoundTravelClassBtnList));
}catch(Exception e) {
e.printStackTrace();
System.out.println("message catch"+e.getMessage());
}
enabledFound=BookDateFlight();
System.out.println("After clicking nxt avil date "+enabledFound);
if(enabledFound==true)
{
break;
}
}
if(enabledFound==false)
{
System.out.println("inside next 7 day");
driver.findElement(By.xpath("//p[#class='next']")).click();
System.out.println("inside next 7 day clicked");
Thread.sleep(10000);
checkFlightAvailabilityToSelectOutBound();
}
}
}
In case of staleelementexception the problem is generally due to the fact that a reference is requested to an element that has been updated or is new (even if maybe it has the same id) and therefore we have an invalid reference to it. It can be solved by asking for a clean reference of the item or adding a wait in the workflow
You can try something like this:
WebDriverWait wait = (WebDriverWait)new WebDriverWait(driver,timeout)
.ignoring(StaleElementReferenceException.class);
wait.until(new ExpectedCondition<Boolean>(){
#Override
public Boolean apply(WebDriver webDriver) {
WebElement element = webDriver.findElement(by);
return element != null && element.isDisplayed();
}
});
Adapting it to you code
it usually occurs when the dom is getting refreshed .try the following explicit wait before doing the click
wait.until(ExpectedConditions.stalenessOf(nxtAvlDate));

Why does Selenium sometimes skip checkboxes?

I'm having troubles regarding webdriver not being able to click checkboxes sometime and just skipping them, both in Firefox and Chrome.
I've tried different solutions such as
click();
action.moveToElement(checkbox).clickAndHold(checkbox).release().perform();
jse.javascriptExecutor(argument[0].click(),checkbox).
Here I provide the Javascript code I have for the click event
...
var selectCorrectOption = function () {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
$(this).find('> input').prop('checked', false);
} else {
$(this).addClass('selected');
$(this).find('> input').prop('checked', true);
}
};
$('.option > .input-container').on('click', selectCorrectOption);
...
the HTML code where it is attached the javascript click event
<div class="input-container selected" data-choice-id="2">
<input type="radio">
</div>
the Java code data uses a data-attribute to access the element is question. Notice also that once the div is clicked, a 'selected' class appears(which is the current state) on the code below.
WebDriverWait wait = new WebDriverWait(driver, 20);
JavascriptExecutor jse = (JavascriptExecutor)driver;
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("[data-choice-id='"+ wrongOptionVal +"']")));
radio=wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("[data-choice-id='"+ wrongOptionVal +"']")));
jse.executeScript("arguments[0].scrollIntoView()", radio);
jse.executeScript("arguments[0].click()", radio);
I expected it to be consistent ,most of the times work, but there are always that one or two times it fails.
I do not know why this happens, I do however know how this can be addressed. You can implement a FluentWait with polling mechanism, which will do three things:
locate the element,
select the radio box,
return getAttribute("class").contains("selected") value.
If getAttribute("class").contains("selected") will result in false the process should repeat.
FluentWait<WebDriver> fluentWait = new FluentWait<>(driver)
.pollingEvery(Duration.ofMillis(300))
.withTimeout(Duration.ofSeconds(10));
fluentWait.until(new Function<WebDriver, Boolean>() {
#Override
public Boolean apply(WebDriver driver) {
WebElement element = driver.findElement(By.cssSelector(radioCssSelector));
element.click();
return element.getAttribute("class").contains("selected");
}
});

ADF input text enable when check box is checked

i am New to ADF, i want display/enable the input text box when checkbox is checked and i should disable when it is unchecked below is the check box ADF code,
ADF Code:
<af:selectBooleanCheckbox label="Apply WITSML Filter" id="sbc11"
autoSubmit="true" contentStyle="margin-left:10px;" valueChangeListener="#{pageFlowScope.welljobs_bean.applyWITSMLFilterIndicator}"/>
Bean:
private transient RichSelectBooleanCheckbox applyWITSMLFilterIndicator;
public void setapplyWITSMLFilterIndicator(RichSelectBooleanCheckbox applyWITSMLFilterIndicator) {
this.applyWITSMLFilterIndicator= applyWITSMLFilterIndicator;
}
public RichSelectBooleanCheckbox getapplyWITSMLFilterIndicator() {
return applyWITSMLFilterIndicator;
}
The input text i want to show:
<af:inputText id="it140" autoComplete="off"
binding="#{pageFlowScope.welljobs_bean.applyWITSMLFilterIndicator.curvesFilter}"
dimensionsFrom="content" editable="inherit" rendered="true"/>
Bean:
private transient RichInputText curvesFilter;
public void setCurvesFilter(RichInputText curvesFilter) {
this.curvesFilter = curvesFilter;
}
public RichInputText getCurvesFilter() {
return curvesFilter;
}
Can anybody please help?
it is also giving me javax.faces.FacesException: javax.el.PropertyNotFoundException: The class 'java.lang.String' does not have the property 'curvesFilter'. Exception
You can do this with EL Expression, partial trigger/autosubmit and ValueChangeEvent.
You want to save the boolean value of the checkedbox inside your bean so you can render or disable the inputText when this value change inside your valueChangeEventListener.
You then want to refresh the inputText so it will display it's new render/disable value by adding the following property to the inputText parent :
partialTriggers="sbc11"
partialTriggers refresh the whole content of a container when an action occur on the element id you give him.
Assuming you want to disable/enable the inputText :
Bean :
public boolean checkboxIsChecked = false; //or private with getter and setter
public void checkBoxValueChange(ValueChangeEvent ve){
this.checkboxIsChecked = ve.getNewValue();
}
Jsf :
<af:selectBooleanCheckbox label="Apply WITSML Filter" id="sbc11"
autoSubmit="true" contentStyle="margin-left:10px;" valueChangeListener="#
{pageFlowScope.welljobs_bean.checkBoxValueChange}"/>
...
<af:inputText id="it140" autoComplete="off"
binding="#{pageFlowScope.welljobs_bean.applyWITSMLFilterIndicator.curvesFilter}"
dimensionsFrom="content" disabled="#{pageFlowScope.welljobs_bean.checkboxIsChecked}"/>
don't forget to add the partialTriggers="CHECKBOXID" to the inputText parent container
For official example see documentation : https://docs.oracle.com/cd/E16764_01/web.1111/b31973/af_lifecycle.htm#CIAHCFJF

Create UI components on page load

I am currently working on oracle adf task flows and regions and I want to create and update some UI components on page load and for this I am using method call activity as default.The problem is that I am getting null values following is my code in the bean that executes on the method call.
package view;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import oracle.adf.view.rich.component.rich.output.RichOutputText;
public class testBean {
public testBean() {
}
public String testMethod() {
// Add event code here...
FacesContext facesContext = FacesContext.getCurrentInstance();
UIViewRoot root = facesContext.getViewRoot();
RichOutputText text = ( RichOutputText )root.findComponent( "r1:ot1" );
text.setValue( "Adding text on run time" );
return "product";
}
}
The set value method returning me null may be it is because the fragment product.jsff which is the view activity is not initiated and the output text with ot1 returning null.
The better approach to achieve the setting of value is to have a property in your bean say: textValue and then bind the value attribute of your ot1 with the property of the bean.
class TestBean{
private String textValue;
public String testMethod() {
textValue = "Adding text on run time";
}
public String getTextValue(){
return textValue;
}
}
Your JSPX would be:
<af:outputText id="ot1" value=#{beanName.textValue}" />

Issue with focus element in GotFocus/Activated event

There is form with text element that should receive focus every time form shown.
In .NET CF Form has no OnShow(n) event
I try to use workaround:
MyForm_GotFocus() // or MyForm_Activated
{
txtTextControl.Text = string.Empty;
txtTextControl.Focus()
}
txtTextControl_GotFocus()
{
txtTextControl.SelectAll()
}
Code for getting form instance:
public static MyForm GetForm
{
get
{
if (s_inst == null || s_inst.IsDisposed)
{
s_inst = new MyForm();
}
return s_inst;
}
}
public static void ShowForm()
{
var frm = GetForm;
frm.Show();
}
1) First time ShowForm (Form instance has been created): txtTextControl emptied and got focus, txtTextControl_GotFocus event raised
2) Second time ShowForm : OK too
3) Third time ShowForm : txtTextControl emptied, but does not get focus
Is there bug or feature? Is there workaround? Show I rewrite ShowForm? Is OpenNETCF.IOC.UI is better solution (50 forms in project)?
I had that same question once.
Set the TabIndex for the control to 0.

Resources