Explore Courses Blog Tutorials Interview Questions
+1 vote
1 view
in DevOps and Agile by (19.7k points)

We're using Selenium with the Java API and some Javascript user extensions. We use a lot of AJAX calls in our app. A lot of our tests fail randomly because sometimes the AJAX calls finish slower than other times so the page isn't fully loaded. We fix that by waiting for specific elements or Thread.sleep. I was trying to find a way to instead just wait for the network traffic to finish. So that we could do this:"some JS button");



That way we can get rid of the thread sleep and have tests pass faster when the server responds faster and not have so many tests fail due to timing issues.

I haven't been able to find a way to do this searching Google. Does anyone have any ideas on how we can accomplish this? (Preferably either through Javascript or the Java API but all suggestions are welcome).

Note: the other variations of "waitFor" are not what I'm looking for. We're already using those in clicks and other things. I'm looking for something that waits for the NETWORK TRAFFIC. Thanks for all the feedback, I'll be trying out a couple of the suggestions, but I'm still open to other ideas.


1 Answer

0 votes
by (62.9k points)

Inject a special javascript that basically overrides all your relevant framework methods and keeps a counter of the number of uncompleted requests, which is incremented upon start and decremented upon completion. Due to the asynchronous nature of javascript, it's not sufficient to keep a Boolean variable, you're likely to end up with race conditions within your own logic.

If you are using visual effects, you most likely want to do this for visual effects too; morphing/fading and other visuals will have a similar drawback.

So we primarily do a regular "click" then always wait for this counter to reach zero again, using javascript. After we got this in place we reduced transient issues to none.

Remember that selenium doesn't return from "click" till all the synchronous are processed, thus you have to be certain to get those counters incremented as a direct consequence of onclick.

For instructions on how to override framework methods you need to consult your framework documentation; we use addMethods in the prototype. It's possible to keep this overriding in a special javascript that is only added to the page when running tests.

If you are interested to learn Selenium on a much deeper level and want to become a professional in the testing domain, check out Intellipaat’s Selenium training course!

Browse Categories