Hi all, during the last two weeks I was dealing with the best solution to wait for both JQuery, Angular and JavaScript (JS) in my Selenium (Java) test codes and finally, I found a significantly stable solution without silly sleep() statements to share with you.

In this period, I searched maybe more than 20 articles and sites to find best and unique solutions and in this article, I combined all solutions in only one method. This is “WaitJQueryAngular()“. When you need to wait for an asynchronous wait, you can use the below methods as your project type.

Then, my solution upgraded by Colm Murphy and he added Angular 5 synchronization method as well. Thanks to him. I updated code snippet on 18 Feb 2019.

I know that you wonder to know what it does? First, it waits JQuery is Ready? and then waits Angular is Ready? and if JQuery or Angular is ready? Then it checks JS is ready? If all of them are ready then the code will continue to run the next statements. Also, I added a control point that checks JQuery and Angular are defined or not. It is important that if the any of them is not defined in the page, code skips asynchronous wait statements. If this control does not exist, we will get a JS error.

You can just add below methods in your code and use “WaitJQueryAngular()” for an asynchronous wait in your test automation codes.

  • Add below JSWaiter utility class into your project.
  • Then, send WebDriver object to JSWaiter Class in a convenient place in your project by adding this line: “JSWaiter.setDriver(driver);”
  • Finally, you can use any of the methods below in your test code:
    • JSWaiter.waitJQueryAngular(); –> Both waits JQuery, Angular, JS
    • waitUntilAngularReady(); –> It only waits Angular and JS
    • waitUntilJQueryReady(); –> It only waits JQuery and JS
    • waitUntilAngular5Ready(); –> Waits for Angular 5 projects

Note: I added waitUntilJSReady(); call both in waitUntilJQueryReady() and waitUntilAngularReady() methods. In this way, if your test site only comprises of Angular or JQuery, you can just use the relevant method to wait asynchronous operations.

Note: You should combine this asynchronous wait solution with the synchronous explicit wait statements to get highest stability in your tests. If you face with a problem, please let me know.

Github Link of a Sample Project: https://github.com/swtestacademy/JSWaiter (It is not updated. Below code snippet is the latest version. You should update JSWaiter class when u clone this project.)

JQuery, Angular, and JavaScript Waiter

Notes:

– For java.net.SocketTimeoutException you can add below line before get() method. It will also wait for Page Load.

Thanks.

-Onur