geb StaleElementReferenceException - selenium

I have just started using geb with webdriver for automating testing. As I understand it, when I define content on a page, the page element should be looked up each time I invoke a content definition.
//In the content block of SomeModule, which is part of a moduleList on the page:
itemLoaded {
waitFor{ !loading.displayed }
}
loading { $('.loading') }
//in the page definition
moduleItems {index -> moduleList SomeModule, $("#module-list > .item"), index}
//in a test on this page
def item = moduleItems(someIndex)
assert item.itemLoaded
So in this code, I think $('.loading') should be called repeatedly, to find the element on the page by its selector, within the context of the module's base element. Yet I sometimes get a StaleElementReference exception at this point. As far as I can tell, the element does not get removed from the page, but even if it does, that should not produce this exception unless $ is doing some caching behind the scenes, but if that were the case it would cause all sorts of other problems.
Can someone help me understand what's happening here? Why is it possible to get a StaleElementReferenceException while looking up an element? A pointer to relevant documentation or geb source code would be useful as well.

It turns out that the problem was that the reference to the element represented by the module itself had become stale by modification, and not the .loading element. I suspect that the exception originated from that line because it was trying to search within the module's base element to find the .loading element. The solution is to load the module at the same time as checking for the element inside it. In this case it would look something like this:
//In the content block of SomeModule, which is part of a moduleList on the page:
itemLoaded { !loading.displayed }
loading { $('.loading') }
//in the page definition
moduleItems {index -> moduleList SomeModule, $("#module-list > .item"), index}
//in a test on this page
waitFor { moduleItems(someIndex).itemLoaded }
Thanks to Marcin on the geb-user mailing list for pointing me in the right direction.

Related

chromeless- Clicking on an element in the next page is not working

On one of my tests I log in and move to the next page.
In the next page when I try to click on the profile element with .click nothing seems to be happening.
When I use the .exists function it returns false.
Why can't chromeless recognize element after changing the DOM?
async func(){
try {
this.chromeless
.goto(this.url)
.click(this.switchToLogIn)
.type(this.email, this.emaillAddressInput)
.type(this.password, this.passwordInput)
.click(this.logInButton )
.click(this.myProfile)
.screenshot()
}
catch(err) {
console.log(err)
}
Anything that was not already available in the DOM tree when the previous action in the chain was performed (with the exception of goto() and possibly some other methods) has to be waited for using the wait() method.
So, assuming that this.myProfile is a CSS selector string for an element to be clicked:
// Unchanged code omitted
.click(this.logInButton)
// Since the previous click loads a new page and/or shows new content, we need to wait
.wait(this.myProfile)
.click(this.myProfile)
Alternatively, the implicitWait Chromeless constructor option could be set to true, as long as that does not affect anything else negatively.

see if the div is present or not in geb

We are using Geb for automation. I have spinner loaded before every page gets loaded. we are using waitFor() , but it takes a long time and the scripts are getting run more than the specified time.The DOM element is
<div classname="loader"></div>
i tried to see if the element is present.
if(!$(".loader").displayed== true)
{}
But i am getting error as ,
geb.waiting.WaitTimeoutException: condition did not pass in 40.0 seconds (failed with exception)
at geb.waiting.Wait.waitFor(Wait.groovy:138)
at geb.waiting.DefaultWaitingSupport.doWaitFor(DefaultWaitingSupport.groovy:51)
at geb.waiting.DefaultWaitingSupport.waitFor(DefaultWaitingSupport.groovy:46)
at geb.Page.waitFor(Page.groovy:516)
at geb.Browser.methodMissing(Browser.groovy:206)
at geb.spock.GebSpec.methodMissing(GebSpec.groovy:56)
at loaderSpec(loaderSpec.groovy:415)
Caused by: Assertion failed:
$(".loader").displayed== false
| | |
| true false
[[[ChromeDriver: chrome on XP (1b3943691dd96ebaf9098b1720c87ee9)] -> css
selector: .loader]]
at loaderSpec(loaderSpec.groovy:415)
at loaderSpec(loaderSpec.groovy:415)
at geb.waiting.Wait.waitFor(Wait.groovy:127)
... 6 more
I am not sure how to check if the div is present or not present. If I extend the time to wait for, I am getting element not found error.
Kindly let me know your input.
Are you checking that the div is visible while you are waiting for the spinner to go away?
I've had an issue exactly like this that plagued me. Here is the solution my coworkers and I came up with:
try{
waitFor(10) { element.isDisplayed() } //wait for spinner to kick in
waitFor() { !element.isDisplayed() } //wait for spinner to go away
} catch(WaitTimeoutException e) {
// if spinner loads & deloads faster than this code is reached
// then WTE will be caught and we dont need to handle the spinner any more
//println(e.printStackTrace())
}
Your boolean expression is more complicated than it needs to be, and in this case you might be noting (!) something you don't mean to be.
in general, you never need to compare booleans. (bool1==true) is the same as saying (bool1).
instead of saying
if(!$(".loader").displayed== true){}
just say:
if($(".loader").displayed){} //to check if the div is displayed
or
if(!$(".loader").displayed){} //to check if the div is not displayed
You can try with code if(!$(".loader")==undefined){}

How to submit a form in Geb (WebDriver) that has no submit button

I'm building up a test in Geb (WebDriver) that has the need to work with a form that has no submit button. From the user's perspective, it is as simple to use as typing in the search term and hitting the enter key on their keyboard.
Using Geb in a purely script form I can get around this by appending the special key code to the text being typed in, as seen in the following:
import org.openqa.selenium.Keys
$('input[id=myInputField]') << "michael"+Keys.ENTER
That works fine. But if I want to use Geb's recommended Page Object pattern (http://www.gebish.org/manual/0.7.1/pages.html#the_page_object_pattern), I don't see what I should do. What do I define in the content section of my EmployeeSearchPage object to duplicate the missing searchButton and its "to" object reference that tells Geb how to handle the resulting page?
class EmployeeSearchPage extends Page {
static url = "http://localhost:8888/directory/"
static at = { title == "Employee Directory" }
static content = {
searchField { $("input[id=myInputField]") }
// THE FOLLOWING BUTTON DOESN'T EXIST IN MY CASE
searchButton(to: EmployeeListPage) { $("input[value='SUBMIT']") }
}
}
I realize that I could add a submit button to the form that I could for the test and use CSS to position it out of the user's view, but why should I have to adapt the app to the test? Things should work the other way around.
I've been evaluating a lot of web testing frameworks and find that this type of form presents a problem for many of them - at least as far as their documentation is concerned.
Any ideas? Thanks!
You don't need to use js integration to achieve what you want.
You can also define methods on your page class, not only content. You could implement a submit method that would do what you are looking for in the following way:
class EmployeeSearchPage extends Page {
static url = "http://localhost:8888/directory/"
static at = { title == "Employee Directory" }
static content = {
searchField { $("input[id=myInputField]")
}
void submitForm() {
searchField << Keys.ENTER
browser.page EmployeeSearchResultsPage
}
}
and then to use it:
to EmployeeSearchPage
searchField << 'michael' // searchField = 'michael' would have the same effect
submitForm()
Geb provides support to execute JavaScript in the context of the browser, details can be found here in the Geb documentation.
You could use this to submit the form exactly like you would submit it using JavaScript in the webapp itself. For example, if you are using jQuery it would be as simple as:
js.exec('$("#myForm").submit()')

Chrome WebDriver hungs when currently selected frame closed

I am working on creation of automated test for some Web Application. This application is very complex. In fact it is text editor for specific content. As a part of functionality it has some pop-up frames. You may open this pop-up? make some changes and save them - closing current frame. May problem is in that fact, that close button situated inside frame will be eliminating. And this force Chrome WebDriver to hung. My first try was like this:
driver.findElement(By.xpath("//input[#id='insert']")).click();
driver.switchTo().defaultContent();
But it hungs on first line after executinh click command as this command close frame.
Then I change to this(I have JQuery on the page):
driver.executeScript("$(\"input#insert\").click()");
driver.switchTo().defaultContent();
But this leads to same result.
Then I use this solution:
driver.executeScript("setTimeout(function(){$(\"input#insert\").click()}, 10)");
driver.switchTo().defaultContent();
And it hungs on second line. Only this solution works:
driver.executeScript("setTimeout(function(){$(\"input#insert\").click()}, 100)");
driver.switchTo().defaultContent();
but only if you don't take into account, that it is unstable - some timing issue may occur.
So may question is there more cleaner and more stable way for switch out from closed frame?
P.S.: executeScript - self defined function to decrease amount of code. It simply executer some js on page.
Update:
I realized I was wrong. This problem is not for all iframes. It's occur when tinyMCE popup used. Situation is exactly like in this topic. So it's doubtful I will find answer here, but who knows. Solution described above will help, but only for very short amount of time, meaning that after several seconds pass chromedriver will hangs on next command.
This is how i would do it in Ruby, hopefully you can change it for java
$driver.find_element(:xpath, "//input[#id='insert']").click
$wait.until {$driver.window_handles.size < 2} #this will "explicitly wait" for the window to close
handles = $driver.window_handles #get available window handles
$driver.switch_to.window(handles[0]) #navigate to default in this case the First window handle
hope this helps
Problem was in this line of tinyMCEPopup code:
DOM.setAttrib(id + '_ifr', 'src', 'javascript:""'); // Prevent leak
Executing this script on page fix hang problem(but possibly creates leaks :) ):
(function() {
var domVar;
if (window.tinymce && window.tinymce.DOM) {
domVar = window.tinymce.DOM
}
else if (window.tinyMCE && window.tinyMCE.DOM) {
domVar = window.tinyMCE.DOM
}
else {
return;
}
var tempVar = domVar.setAttrib;console.log(123)
domVar.setAttrib = function(id, attr, val) {
if (attr == 'src' && typeof(val)== 'string' &&(val + "").trim().match(/javascript\s*:\s*("\s*"|'\s*')/)) {
console.log("Cool");
return;
}
else {
tempVar.apply(this, arguments);
}
}
}());
Bug and solution also described here
Note. Code above should be added to parent frame, not into popup frame.

DojoX Mobile ListItem load HTML via AJAX and then remove from DOM

Let's say in a view I have a DojoX Mobile ListItem that is pulling an HTML view fragment into the DOM via AJAX and then transitioning to that view. Assume this is all working fine.
Now, I go back to the initial view that had that ListItem on it and click some other button that destroys that view node from the DOM. If I now click on that ListItem that previously loaded that view node into the DOM (which has now been removed), it will try to transition to a view that doesn't exist. It doesn't know that it has been removed.
Is there some type of way to tell a ListItem that it needs to fetch the HTML again because what was previously fetched no longer exists? I am not seeing anything about doing this in any documentation anywhere. I don't think a code sample is really necessary here, but I can provide a minimal one if necessary.
I went a different route and left the view exist in the DOM, and simply made a function that clears all sensitive data out of the view.
Okay, in this case, i guess you could hook the onShow function of your ListItem container(or any other onchange event). Create a listener for said handle to evaluate if your item needs reloading. Following is under the assumtion that it is the item.onclick contents showing - and not the label of your item which contains these informations
Or better yet, do all this during initialization so that your ListItem container will be an extended with custom onClick code.
Seems simple but may introduce some quirks, where/when/if you programatically change to this item, however here goes:
function checkItem() {
// figure out if DOM is present and if it should be
if( isLoggedIn() ) {
this.getChildren().forEach(function(listitem) {
if( dojo.query("#ID_TO_LOOK_FOR", listitem.domNode).length == 0 ) {
// this references the listItem, refresh contents.
// Note: this expects the listitem to be stateful, have no testing environment at time being but it should be
listitem.set("url", listitem.url);
}
});
}
}
Preferably, set this in your construct of the container for your ListItems
var listItemParent = new dojox.mobile.RoundRectList({
onShow : checkItem,
...
});
Or create listener
var listItemParent = dijit.byId('itemRegistryId');
// override onClick - calling inheritance chain once done
dojo.connect(listItemParent, "onClick", listItemParent, checkItem);