How to Handle AJAX Calls and Loading Spinners in Selenium

How to Handle AJAX Calls and Loading Spinners in Selenium

In a fast-growing digital world, we expect modern web applications to be dynamic and efficient in real-time. This is mainly done via AJAX (Asynchronous JavaScript and XML) that makes the parts to update on web page without complete-page reload. While this may improve the user experience, it also creates problems in software testing. When you first start with automation or during your Selenium Training in Bangalore you most certainly would have had problems handling AJAX calls and loading spinners. This blog is on How to Handle AJAX Calls and Loading Spinners in Selenium which will help you to be more confident in your software testing. 

How to Deal with AJAX Calls

Using AJAX, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display of an existing page. Because the path is asynchronous, it means that elements may become available for interaction at different times of execution creates a race condition or timing problem in your test scripts. When your script tries to identify an element before it has completely loaded, the test might fail.

Techniques to Handle AJAX Calls

1. Using Explicit Waits

Explicit Waits — One of the most robust way to handle AJAX calls in Selenium In the above case one more method which is used by Selenium are Explicit waitshwndselenium- An explicit wait instruct WebDriver to pause for a certain amount of time, or until a certain condition occurs before proceeding any further. To give an example, we can wait for visibility of some web element or spinner to go away before running next step in the test.

Here’s an example:

“`java

WebDriverWait wait = new WebDriverWait(driver, Duration.ZERO); ofSeconds(10));

wait. until(ExpectedConditions. ExpectedConditions. invisibilityOfElementLocated(By. id(“loadingSpinner”)));

“`

This code shows Selenium waiting until the loading spinner with an ID of `loadingSpinner` is no longer visible before progressing to the next step. This is done so we make sure AJAX call has been completed and the page is ready for some more interactions.

2. Using Fluent Waits

Fluent Waits are the more dynamic way of providing waits as compared to explicit wait. This way you can define how long to wait for a condition and how often are we checking the condition this is called fluent waits. In this way, it is very handy while managing any unpredictable AJAX calls.

Below example provides the fluent wait use case:Ways to Implement Fluent Wait;

“`java

DefaultTimeOut = 30; Wait wait = new FluentWait<>(driver

. withTimeout(Duration. ofSeconds(30))

. pollingEvery(Duration. ofSeconds(5))

. supressing(NoSuchElementException. class);

WebElement element = wait. until(driver -> driver. findElement(By. id(“dynamicElement”)));

“`

For instance, the following instructs Selenium to wait for an element called `dynamicElement` with ID for 30 seconds: conducted each every five seconds. You should consider implicit wait if you have lot of elements to handle which is need not be mandatory while fluent waits are good for handling elements that load at unpredictable times.

3. Using JavaScript Executor

Alternatively, you can use the JavaScript Executor in Selenium to listen for AJAX activity directly. This way your code can find when AJAX calls are finished and prevent the next actions unless the page is fully loaded.

Here’s an example:

“`java

JavascriptExecutor js = (JavascriptExecutor)driver;

  1. executeScript(“return jQuery. active == 0”);

“`

This script will verify any requests made via jQuery AJAX. If `true`, all AJAX calls have finished. This is especially helpful for more complicated web apps that involve a lot of AJAX.

Handling Loading Spinners

A loading spinner is a visual and animated hint that an AJAX request or process has started. You cannot expect that the tests do not fail, since it is necessary to wait until those spinners disappear before interacting with the webpage.Selenium Training in Marathahalli covers real life scenarios where majority of the challenge resides and most often these are part of software testing which also includes Selenium.

  1. As you can see that Spinner has gone.

The most naive way to deal with a loading spinner is at the end of its cycle. To do this you may use an explicit wait —

“`java

WebDriverWait wait = new WebDriverWait(driver, Duration. ofSeconds(20));

wait. until(ExpectedConditions. invisibilityOfElementLocated(By. id(“spinner”)));

“`

This code will wait till 20 seconds maximum for the spinner to disappear and then moves forward with your test script.

  1. Waiting Until Elements are Clickable

Occasionally, you may need to wait on the element,(and spinner is hidden) but business interaction cannot be made until that part of system operation has completed. In that case, better to wait for it be Click able.

“`java

WebDriverWait wait = new WebDriverWait(driver, Duration. ofSeconds(10));

WebElement element = wait. until(ExpectedConditions. elementToBeClickable(By. id(“submitButton”)));

element.click();

“`

It guarantees that it is visible and enabling the element before selenium can do any activity on them.

  1. Combining Techniques

So, in some scenarios advance techniques works whereas for the rest you need to combine those. For instance, one can wait for the spinner to get disappeared and then hits a specific element clickable. The multilayered setup provides your tests a better trustworthiness, they are easier to deal with and allow you to cover more possibilities.

Best Practices in Software Testing with Selenium

  1. Use reasonable timeouts: Define your timeout thresholds based on the typical response times of your app. Try to not run very long timeouts that can slow your tests or too short ones causing unnecessary failures.For those looking to enhance their skills in this area, a Software Testing Course in Bangalore can provide valuable insights into effective timeout management and other testing best practices.
  2. Avoid `Thread. sleep()`: While `Thread. Although `sleep()` sounds like a simple solution, it actually introduces arbitrary delays into your tests and that can make the less efficient. Instead, use dynamic waits that wait for when the page is truly ready.
  3. Performing Across Environments: AJAX behavior may differ between environments (e. g., development vs production) These differences mean your tests have to be more robust, so as to not inadvertently fail the test on an implementation detail.
  4. Browser Developer Tools: Using browser developer tools helps monitor AJAX calls and debugging waits for better testing.

In software testing, it is a common scenario that developers use AJAX to fetch data when the user enters some values and loading spinners are also added on the screen while calling any service. This can make our selenium test script unreliable unless we have support for handling such calls in Selenium(WebDriver). You may use explicit waits, fluent wait or JavaScript execution to address these and ensure your tests do not trip over because of dynamic content. By training and polishing these methods, possibly through a Training Institute in Bangalore, you obtain at attributes above all with regards to the challenges. This will not only help you to be more confident in your software testing but also achieve better automation skills thus increasing productivity.

Also Check: Selenium Interview Questions and Answers