Start Selenium test after Javascript finish - java

I´m using Selenium, and I need to start testing my page not only when the page is render, but when all javascript initialization is done. I´m looking to avoid Race condition on my test because some elements are not initialized properly yet.
Simple question there´s any way to ask the DOM when all javascript render has finish?.
We know when render has done because of onDocumentReady. But then, we can start initializing some javascripts, and doing some business logic.
I want to know if there´s any mechanism to know when all javascript execution has finish.
I read the use of promise object for some async initialization, but I was looking for a more generic way to know it.

There is no generic way to know that JavaScript code has finished doing its initialization. A single page can load dozens of JavaScript libraries that can all do their own thing. Even if you can detect that an initial Ajax operation has completed, there is generally no way to know that this initial operation won't be followed by other operations that are also part of the initialization.
What you have to do is find a way to determine that, as far as your test is concerned, the page is initialized enough for the test to start. How you do this depends on the JavaScript code that is running on your page. Here's an example. For some of my applications I use DataTables to manage some of my tables. The data that appears in a table is loaded through an Ajax call. For some tests, I know that once the data is loaded, the table will have X number of rows so I wait for this many rows to appear in the table and then proceed with the test. This works for some tests. For other tests that do more complicated testing, I have to register an event handler and listen for a table redraw event before the test can proceed. If the only thing I'm testing is the table, it would be wasteful to wait until other stuff on the page has finished initializing.

Related

Spring StateMachine How do I know if a transistion is rejected due to failed guard or action?

I have the same question as in the topic below, but I'm not so sure if my approach is wrong.
How do I know if a guard rejected a transistion
My app is a linear step-by-step strategy board game with several different game settings. I've decided to use Spring StateMachine to solve as in my opinion (and so far) it solves a lot little code-related organisational problems But now I'm stacked
The problem I have run into is that I can't say if my event passed all the guards and transition occurs. I just get true-flag when an event is added to the queue
The approach I'm following is passing data via event-context, validation of one with guards and apply changes using actions
transitions
.withExternal().source(SPEECHES).target(VOTING).event(VOTING_EVENT)
.guard(Guard.and(
guards.get(NoVotesFromSuspectedGuard.QUALIFIER),
guards.get(NoSelfVotingGuard.QUALIFIER),
guards.get(NoDeadParticipantsVotingGuard.QUALIFIER),
guards.get(NoVotingForDeadParticipantsGuard.QUALIFIER),
votingOutOfParticipantListGuardFactory.get(NUMBER_OF_PLAYERS),
guards.get(VotingBasedOnPreviousOneGuard.QUALIFIER)
))
.action(actions.get(CalculateVotingAction.QUALIFIER))
As I understand now, there is no possibility to notify event-supplier about failed guard evaluation. If so, just let me know and I will switch to another SM implementation. But if there is any possibility of solving my problem, please help me.
The behaviour I expect is any meta info of failed guard (to build formatted error message)
You can use some context flag, for example context.put("NoVotesFromSuspectedGuard", false) when "NoVotesFromSuspectedGuard" isn't success and then you can check this variable in your invoke code context.getExternalVariables().get("NoVotesFromSuspectedGuard", Boolean.class).
Also, in Spring State Machine you can declare ActionListener bean, which contains some different methods for StateMachine events monitoring.
For more information, you can see Habr(Russian)

WebDriver Explicit wait in Page Object model

We currently have a big selenium junit project which uses the page object model. We make use of the #FindBy annotation to declare our WebElements. Now when we run the tests, we randomly get the NoSuchelementException, which means the page might not have finished loading. We don't want to use an implicit wait because that won't provide a complete solution (an element might be present in the DOM but not interactable yet). An explicit wait might solve this problem. However, how do we use it in this page model architecture without having to take away the #FindBy annotation? This might have been asked before, but I don't seem to find any solutions yet.
There's a 4 ways I've see you can do this. None of them are fun, although, they get better as you go along (and more complicated to program)
Copy your selector into an explicit wait
Put your #FindBy on a List<WebElement> and wait until the size is not 0.
Create a function that accepts a WebElement and calls isDisplayed() (or some other non-action function) until it doesn't throw an exception
A final solution you could implement is to use the Decorator pattern around WebElement. This means that you will need to create your own FieldDecorator, and then use that decorator when you initialize your decorated WebElements. The decorated webelement would have a exists() function that would basically be a try/catch around NoSuchElementExceptions.
If you are confused about any of these solutions, I can provide code for them, but I think it really good practice to learn how WebElementWait and Page Objects really work (by implementing your chosen solution), so I won't post it now.

Cancelling method calls when the same method is called multiple time

I think there's probably a name for what I'm describing here, but I don't know it. So my first question would be to know the name of this technique.
Here's an example: suppose you're implementing live search on a web page. Everytime the user types in the search box, you fire a new search query, and the results are updated as often as possible.
This is a stupid thing to do because you'll send much more queries than you actually need. Sending a request once per 2-3 letters or at most once per 100 ms is probably sufficient.
A technique is thus to schedule the queries to be executed soon after a key is typed, and if there are still queries that were planned but not executed, cancel them since they're obsolete now.
Now more specifically, are there specific patterns or librairies for solving this problem in Java ?
I had to solve the problem in a Swing app, and I used an ExecutorService, which returned ScheduledFutures that I could cancel. The problem is that I had to manually create a Runnable for each method call I wanted to "buffer", and keep track of each Future to cancel it.
I'm sure I'm not the first person to implement something like this, so there must be a reusable solution somewhere ? Possibly something in Spring with annotations and proxies ?
Given the other answers, and after some searching, it seems there's indeed no library that does what I wanted.
I created one and put it on GitHub. Future readers of this question may find it interesting.
https://github.com/ThomasGirard/JDebounce
I don't think it's very good yet but at least it works and can be used declaratively:
#Debounce(delayMilliseconds = 100)
public void debouncedMethod(int callID, DebounceTest callback) { }
This is not solvable in Java without using some extra infrastructure like you did with executor and futures. It is not possible to solve this in syntactically concise manner in Java.
You will always need some sort of method result wrapper, because the mechanism returns immediately but the actual result is retrieved later. In your case this was accomplished via Future.
You will always need to be able to specify code to be executed in a manner that will allow delayed execution. In most languages this is accomplished using function pointers or function values or closures. In Java, lacking these language features, this is usually accomplished by passing an object that implements some sort of interface such as Runnable, Callable, that allows delayed execution of a block of code. There are other options but none of them are simple, such as using a dynamic proxy.
tl;dr
Can't do this in concise manner in Java.
What you need is called debouncing. You should check the jQuery Throttle/Debounce plugin (which is btw totally independent of jQuery except for using the same namespace). What you need is covered by the debounce part:
Using jQuery throttle / debounce, you can pass a delay and function to
$.debounce to get a new function, that when called repetitively,
executes the original function just once per “bunch” of calls,
effectively coalescing multiple sequential calls into a single
execution at either the beginning or end.
Underscore.js has the same method:
_.debounce(function, wait, [immediate])
Creates and returns a new debounced version of the passed function
which will postpone its execution until after wait milliseconds have
elapsed since the last time it was invoked. Useful for implementing
behavior that should only happen after the input has stopped arriving.
For example: rendering a preview of a Markdown comment, recalculating
a layout after the window has stopped being resized, and so on.
// example: debounce layout calculation on window resize
var lazyLayout = _.debounce(calculateLayout, 300);
$(window).resize(lazyLayout);
[Edit]
I mistakenly read "Javascript" instead of Java. Actual Java solution was written by OP afterwards.

present live data in JTextArea using Swing

Don't know if it's stupid or reasonable question.
I have methods which returns float/int data (x,y,z positions) of the P5 Glove (if you know it).
I also have update method which responds to the glove pulling.
All i'm having trouble with is creating UI and presenting the data in text area, means every update the text areas presenting the data refreshed and present the data.
Since code isn't that short here are links to the class: Details presentation methods and update
let's say for now I want to present showActiveLedPosX() method which returns the X position as String.
the other classes are glove (using glove methods and creating glove object and UI).
Should I use different class for UI? or should I do it all on ShowGloveValues class
I've never created UI and therefore I'm kinda clueless here, Tried to read about it on numerous resource sites and still couldn't achieve what's needed.
1. Keep the UI thread apart from the Non-UI thread.
2. Event Dispatcher Thread is the UI thread, keep this thread to handle your UI only.
3. You can also use SwingWorker for this.
4. Swing is based on Mode View Controller. Moreover its better to divide your app packages also on the basis of MVC.
eg:
com.vivek.model; // Class responsible for Business Logic and Data
com.vivek.view; // Class responsible for the UI

Seeing the results ofHttpUnitOptions.setLoggingHttpHeaders(true); internally to an HttpUnit project?

My goal is to be able to use HttpUnit to crawl around my webpage and see what is and is not firing in the background... I have gotten it to connect to my page, and if I set
HttpUnitOptions.setLoggingHttpHeaders(true);
I see the sorts of background calls that I care about. However, I do not know how to see those interactions within the program. most of the getText and getInputStream calls fo the WebResponse object seem to just be the HTML call, and don't log the various javascript calls that fire in the background. Is there a way to get a list of all of the things going on in the background? HttpUnit's documentation seems sparse.
Thanks!
I just stumbled upon the answer. it looks like you need to make a class that implements WebClientListener, and then call wc.addClientListener(new YourListener()); where wc is a WebClient.
I don't delete this so others can see...and perhaps there is more nuance to it than that.

Categories

Resources