Hi all, during the last two weeks I was dealing with the best solution to wait for both JQueryAngular 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 asynchronous wait, you can use below methods as your project type.

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 next statements. Also, I added a control 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 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 you test code:
    • JSWaiter.waitJQueryAngular(); –> Both waits JQuery, Angular, JS
    • waitUntilAngularReady(); –> It only waits Angular and JS
    • waitUntilJQueryReady(); –> It only waits JQuery and JS

NoteI 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

JQuery, Angular, and JavaScript Waiter

public class JSWaiter {

    private static WebDriver jsWaitDriver;
private static WebDriverWait jsWait;
private static JavascriptExecutor jsExec; //Get the driver
public static void setDriver (WebDriver driver) {
jsWaitDriver = driver;
jsWait = new WebDriverWait(jsWaitDriver, 10);
jsExec = (JavascriptExecutor) jsWaitDriver;
} //Wait for JQuery Load
public static void waitForJQueryLoad() {
//Wait for jQuery to load
ExpectedCondition<Boolean> jQueryLoad = driver -> ((Long) ((JavascriptExecutor) jsWaitDriver)
.executeScript("return jQuery.active") == 0); //Get JQuery is Ready
boolean jqueryReady = (Boolean) jsExec.executeScript("return jQuery.active==0"); //Wait JQuery until it is Ready!
if(!jqueryReady) {
System.out.println("JQuery is NOT Ready!");
//Wait for jQuery to load
jsWait.until(jQueryLoad);
} else {
System.out.println("JQuery is Ready!");
}
} //Wait for Angular Load
public static void waitForAngularLoad() {
WebDriverWait wait = new WebDriverWait(jsWaitDriver,15);
JavascriptExecutor jsExec = (JavascriptExecutor) jsWaitDriver; String angularReadyScript = "return angular.element(document).injector().get('$http').pendingRequests.length === 0"; //Wait for ANGULAR to load
ExpectedCondition<Boolean> angularLoad = driver -> Boolean.valueOf(((JavascriptExecutor) driver)
.executeScript(angularReadyScript).toString()); //Get Angular is Ready
boolean angularReady = Boolean.valueOf(jsExec.executeScript(angularReadyScript).toString()); //Wait ANGULAR until it is Ready!
if(!angularReady) {
System.out.println("ANGULAR is NOT Ready!");
//Wait for Angular to load
wait.until(angularLoad);
} else {
System.out.println("ANGULAR is Ready!");
}
} //Wait Until JS Ready
public static void waitUntilJSReady() {
WebDriverWait wait = new WebDriverWait(jsWaitDriver,15);
JavascriptExecutor jsExec = (JavascriptExecutor) jsWaitDriver; //Wait for Javascript to load
ExpectedCondition<Boolean> jsLoad = driver -> ((JavascriptExecutor) jsWaitDriver)
.executeScript("return document.readyState").toString().equals("complete"); //Get JS is Ready
boolean jsReady = (Boolean) jsExec.executeScript("return document.readyState").toString().equals("complete"); //Wait Javascript until it is Ready!
if(!jsReady) {
System.out.println("JS in NOT Ready!");
//Wait for Javascript to load
wait.until(jsLoad);
} else {
System.out.println("JS is Ready!");
}
} //Wait Until JQuery and JS Ready
public static void waitUntilJQueryReady() {
JavascriptExecutor jsExec = (JavascriptExecutor) jsWaitDriver; //First check that JQuery is defined on the page. If it is, then wait AJAX
Boolean jQueryDefined = (Boolean) jsExec.executeScript("return typeof jQuery != 'undefined'");
if (jQueryDefined == true) {
//Pre Wait for stability (Optional)
sleep(20); //Wait JQuery Load
waitForJQueryLoad(); //Wait JS Load
waitUntilJSReady(); //Post Wait for stability (Optional)
sleep(20);
} else {
System.out.println("jQuery is not defined on this site!");
}
} //Wait Until Angular and JS Ready
public static void waitUntilAngularReady() {
JavascriptExecutor jsExec = (JavascriptExecutor) jsWaitDriver; //First check that ANGULAR is defined on the page. If it is, then wait ANGULAR
Boolean angularUnDefined = (Boolean) jsExec.executeScript("return window.angular === undefined");
if (!angularUnDefined) {
Boolean angularInjectorUnDefined = (Boolean) jsExec.executeScript("return angular.element(document).injector() === undefined");
if(!angularInjectorUnDefined) {
//Pre Wait for stability (Optional)
sleep(20); //Wait Angular Load
waitForAngularLoad(); //Wait JS Load
waitUntilJSReady(); //Post Wait for stability (Optional)
sleep(20);
} else {
System.out.println("Angular injector is not defined on this site!");
}
} else {
System.out.println("Angular is not defined on this site!");
}
} //Wait Until JQuery Angular and JS is ready
public static void waitJQueryAngular() {
waitUntilJQueryReady();
waitUntilAngularReady();
} public static void sleep (Integer seconds) {
long secondsLong = (long) seconds;
try {
Thread.sleep(secondsLong);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Selenium Webdriver wait for JavaScript JQuery and Angular的更多相关文章

  1. selenium使用Xpath+CSS+JavaScript+jQuery的定位方法(治疗selenium各种定位不到,点击不了的并发症)

    跟你说,你总是靠那个firebug,chrome的F12啥的右击复制xpath绝对总有一天踩着地雷炸的你死活定位不到,这个时候就需要自己学会动手写xpath,人脑总比电脑聪明,开始把xpath语法给我 ...

  2. 转:selenium webdriver 执行javascript代码

    在用selenium webdriver 编写web页面的自动化测试代码时,可能需要执行一些javascript代码,selenium本身就支持执行js,我们在代码中import org.openqa ...

  3. selenium webdriver ——执行javascript代码

    在代码中import org.openqa.selenium.JavascriptExecutor;就可以使用executeScript.executeAsyncScript这两个方法了 execut ...

  4. selenium webdriver——JavaScript警告窗处理

    在WebDriver中处理JavaScript所生成的alert.confirm以及prompt,具体方法是使用switch_to_alert()方法定位到alert.confirm以及 prompt ...

  5. [selenium webdriver Java]使用自定义条件同步测试

    Selenium WebDriver可以结合ExpectedCondition类来定义自己期望的条件 创建一个新的ExpectedCondition接口,必须实现apply方法 等待元素出现 publ ...

  6. selenium webdriver (python)的基本用法一

    阅在线 AIP 文档:http://selenium.googlecode.com/git/docs/api/py/index.html目录一.selenium+python 环境搭建........ ...

  7. selenium webdriver (python)大全

    webdriver的简介 硒2.0的主要新功能是集成的webdriver的API.webdriver的设计除了解决一些seleniumr-RC API的一些限制,与webdriver 的整合,将提供一 ...

  8. Selenium WebDriver(Python)API

    1.通过示例介绍Selenium-WebDriver 一个简单的入门方法就是这个例子,它在Google上搜索术语“Cheese”,然后将结果页面的标题输出到控制台. java csharp pytho ...

  9. 深入理解jQuery、Angular、node中的Promise

    最初遇到Promise是在jQuery中,在jQuery1.5版本中引入了Deferred Object,这个异步队列模块用于实现异步任务和回调函数的解耦.为ajax模块.队列模块.ready事件提供 ...

随机推荐

  1. 笔记 : WampServe加装PHP版本(7.2.3)为例

    1.由于正在学习Laravel框架,服务器wamp,Composer已搭建完成,但在安装laravel installer之后使用laravel new blog,报错为"This pack ...

  2. java.lang.NoClassDefFoundError: org/hibernate/QueryTimeoutException

    在做ssh整合的时候报错:java.lang.NoClassDefFoundError: org/hibernate/QueryTimeoutException org.springframework ...

  3. tp连贯操作

    链接数据库 首先写配置文件 复制concentration.php中的 /* 数据库设置 */ 'DB_TYPE' => '', // 数据库类型 'DB_HOST' => '', // ...

  4. python中impyla包报'TSocket' object has no attribute 'isOpen'错误

    经搜索得知,是thrift-sasl的版本太高了(0.3.0),故将thrift-sasl的版本降级到0.2.1 pip install thrift-sasl==0.2.1 经测试impyla 可以 ...

  5. vss使用笔记

    一.四大代码/文档管理软件 (1)     git:具有PR(push request)特性,推送请求.需要负责人审核后才能推送.另外,在推送过程中,git会预编译(合并),分布式代码管理(客户端本地 ...

  6. 33网络通信之Epoll模型

    多路复用并发模型  -- epoll 监控事件 events EPOLLIN                  fd可读 EPOLLOUT              fd可写 EPOLLPRI     ...

  7. 20155228 2016-2017-2 《Java程序设计》第1周学习总结

    20155228 2016-2017-2 <Java程序设计>第1周学习总结 教材学习内容总结 这部分内容是以教材为基础,根据个人的理解来描述的,有的地方的理解和表述可能不规范甚至不正确, ...

  8. MVC中的Ajax与增删改查(二)

    上一篇记录的是前台操作,下面写一下后台 ,本来自认为是没有必要做补充,毕竟思路啥的都有,实际上在做删除操作的时候,折腾了一天,还是自己太嫩,逻辑不够严谨,这里作下记录. 关于表结构这里再作下说明: ① ...

  9. STL容器之list

    [1]list简介 实质上,list容器就是一个双向链表,可以高效地进行插入.删除操作. [2]list链表常用方法 (1)构造.赋值.清空.删除.插入.判空等 应用示例代码如下: #include ...

  10. c# Applicatcontext类

    Application类(位于System.Windows.Forms命名空间)公开了Run方法,可以调用该方法来调度应用程序进入消息循环.Run方法有三个重载 1.第一个重载版本不带任何参数,比较少 ...