This example will show you how to execute jQuery script in selenium webdriver automation test script. When your web page contain jQuery js file, it will execute the jQuery script directly, when the web page do not contain jQuery js file, it can inject a local jQuery js file and then execute the jQuery script.
1. Run jQuery In Selenium WebDriver Example.
There are two web page as below. The page content is same, the only difference is that one page contain jquery-3.3.1.min.js the other do not contain it.
- https://www.dev2qa.com/demo/jquery/hide-show-contain-jquery.html, this page contains jQuery include script as below. So we can execute jQuery directly in selenium webdriver with this page.
<script type=”text/javascript” src=”./jquery-3.3.1.min.js”></script> - https://www.dev2qa.com/demo/jquery/hide-show-not-contain-jquery.html, this page do not contain jQuery include script. So we should inject a local version of jQuery script before execute it.
This example run two test case method in a TestNG class. The two test method will ordered by it’s priority attribute value. You can refer TestNG Tutorial Article List to learn more about TestNG.
2. Example ScreenShot And Source Code.
If you can not watch the above video, you can see it on the youtube URL https://youtu.be/TjrIWpubnpY
TestRunjQuery.java
package com.dev2qa.webdriver; import org.testng.annotations.Test; import org.testng.annotations.BeforeClass; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.AfterClass; public class TestRunjQuery { private ChromeDriver chromeDriver = null; private JavascriptExecutor javascriptExecutor; @BeforeClass public void beforeClass() { // Initialize google Chrome webdriver. if(chromeDriver == null) { //Set string variable value to Chrome Driver executable file path. String chromeDriverPath = "/Users/zhaosong/Documents/WorkSpace/tool/chromedriver"; //Assign chromeDriverPath to system property "webdriver.chrome.driver" System.setProperty("webdriver.chrome.driver", chromeDriverPath); //Create a new instance chromeDriver = new ChromeDriver(); javascriptExecutor = (JavascriptExecutor)chromeDriver; } } @AfterClass public void afterClass() { // Quit the google Chrome driver. if(chromeDriver != null) { chromeDriver.quit(); chromeDriver = null; } } @Test(priority = 0) public void runjQueryScript() { // This web page contains the jQuery js file. chromeDriver.get("https://www.dev2qa.com/demo/jquery/hide-show-contain-jquery.html"); WebElement button = chromeDriver.findElementById("showHideDiv"); if(isElementVisible(button)) { if(isjQueryLoaded(chromeDriver, 10)) { runjQueryJavaScipt(); } } } @Test(priority = 1) public void runAfterInjectjQueryScript() { // This web page do not contains the jQuery js file. So we need to inject jQuery js file first. chromeDriver.get("https://www.dev2qa.com/demo/jquery/hide-show-not-contain-jquery.html"); // Inject and load jquery script first. After inject jQuery script the animation effect can be shown again. // You can comment below code to see the different. injectjQuery(); if(isjQueryLoaded(chromeDriver, 10)) { runjQueryJavaScipt(); } } /* This method will run a short jQuery script with JavascriptExecutor object. */ private void runjQueryJavaScipt() { // This is the jQuery js script string that will be executed by js executor object. // we do not click the button to trigger it. Just execute the script directly. String script = "// Get div display attribute value.\n" + " var display = $(\".div\")[0].style.display;\n" + " if(display=='none')\n" + " {\n" + " $(\".div\").show(1000);\n" + " }else\n" + " {\n" + " $(\".div\").hide(1000);\n" + " }"; // Execute above jQuery script for the first time to hide the div. javascriptExecutor.executeScript(script); // Then sleep 3 seconds too see the effect. try { Thread.sleep(3000); }catch(InterruptedException ex) { ex.printStackTrace(); } // Execute above jQuery script for the second time to show the div again. javascriptExecutor.executeScript(script); // Then sleep 3 seconds to see the effect. try { Thread.sleep(3000); }catch(InterruptedException ex) { ex.printStackTrace(); } } /* Check and return whether the web element is visible or not. */ public boolean isElementVisible(WebElement element){ boolean ret = true; try { // Create visibility expected condition. ExpectedCondition condition = ExpectedConditions.visibilityOf(element); // Create WebDriver wait object. WebDriverWait webDriverWait = new WebDriverWait(chromeDriver, 30); // WebDriver wait until the expected condition is true. webDriverWait.until(condition); }catch(TimeoutException ex) { ex.printStackTrace(); ret = false; }finally { return ret; } } /* Check whether jQuery script file has been loaded in the web browser or not. */ public boolean isjQueryLoaded(WebDriver driver, int waitTime) { boolean ret = true; try { System.out.println("Check jQuery loading status. "); WebDriverWait webDriverWait = new WebDriverWait(chromeDriver, 30); // Create a new expected condition. ExpectedCondition condition = new ExpectedCondition<Boolean>() { // Implement apply method. public Boolean apply(WebDriver webDriver) { JavascriptExecutor jsExecutor = (JavascriptExecutor) webDriver; // This scrpit will get jQuery ready state. String scriptString = "return document.readyState"; String readyState = jsExecutor.executeScript(scriptString).toString(); System.out.println("Document Ready State: " + readyState); // This script can return jQuery script load state. scriptString = "return !!window.jQuery && window.jQuery.active == 0"; return (Boolean) jsExecutor.executeScript(scriptString); } }; // Get the check result in a boolean value. Boolean checkResult = (Boolean)webDriverWait.until(condition); ret = checkResult.booleanValue(); }catch(TimeoutException ex) { ex.printStackTrace(); ret = false; }finally { if(ret) { System.out.println("jQuery has been loaded in the page."); }else { System.out.println("jQuery has not been loaded in the page."); } return ret; } } /* This method will inject a local jQuery script file into WebDriver Chrome browser that browse current web page. */ private boolean injectjQuery() { boolean ret = true; try { // Read out the local jQuery script content string. StringBuffer jQueryStringBuf = new StringBuffer(); File file = new File("/Users/zhaosong/Documents/WorkSpace/dev2qa.com-example-code/JavaScriptExampleWorkspace/jQueryWorkspace/jQueryProject/lib/jquery-3.3.1.min.js"); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line = br.readLine(); while(line != null) { jQueryStringBuf.append(line); line = br.readLine(); } // Execute the jquery js content string to enable it. javascriptExecutor.executeScript(jQueryStringBuf.toString()); }catch(IOException ex) { ret = false; ex.printStackTrace(); }catch(Exception ex) { ret = false; ex.printStackTrace(); }finally { if(ret) { System.out.println("jQuery has been injected successfully."); }else { System.out.println("jQuery has not een injected successfully."); } return ret; } } }
can you please share the below file
/Users/zhaosong/Documents/WorkSpace/dev2qa.com-example-code/JavaScriptExampleWorkspace/jQueryWorkspace/jQueryProject/lib/jquery-3.3.1.min.js