Async script execution in Selenium Java - Build an Automation Script
import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; public class AsyncScriptExecutionTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); try { driver.get("https://example.com/async-test-page"); // Wait until the button is clickable WebElement startButton = wait.until(ExpectedConditions.elementToBeClickable(By.id("startAsync"))); startButton.click(); JavascriptExecutor js = (JavascriptExecutor) driver; // Execute async script that waits 3 seconds then returns 'done' String result = (String) js.executeAsyncScript( "var callback = arguments[arguments.length - 1];" + "setTimeout(function() { callback('done'); }, 3000);" ); if (!"done".equals(result)) { throw new AssertionError("Expected 'done' but got: " + result); } System.out.println("Test passed: Async script returned 'done'"); } catch (Exception e) { e.printStackTrace(); } finally { driver.quit(); } } }
This test script uses Selenium WebDriver with Java to automate the manual test case.
First, it sets up ChromeDriver and opens the test page URL.
It waits explicitly for the button with id 'startAsync' to be clickable, then clicks it.
Next, it uses executeAsyncScript to run JavaScript that waits 3 seconds asynchronously and then calls the callback with 'done'.
The returned result is captured and asserted to equal 'done'.
Finally, the driver quits to close the browser.
This approach ensures the async JavaScript runs properly and the test verifies the expected output.
Now add data-driven testing with 3 different wait times (1000ms, 2000ms, 3000ms) and verify the async script returns 'done' each time.
Practice
executeAsyncScript in Selenium Java?Solution
Step 1: Understand async JavaScript in Selenium
Async scripts allow waiting for tasks like AJAX calls or timers to finish before continuing.Step 2: Role of
This method runs JavaScript that signals completion via a callback, so Selenium waits properly.executeAsyncScriptFinal Answer:
To run JavaScript code that waits for asynchronous tasks to complete before returning. -> Option DQuick Check:
Async script waits for tasks = A [OK]
- Confusing async with synchronous script execution
- Thinking it pauses test for fixed time
- Assuming it runs only once at browser start
Solution
Step 1: Identify async script syntax
Async scripts require a callback function as the last argument to signal completion.Step 2: Check each option
driver.executeAsyncScript("var callback = arguments[0]; setTimeout(() => callback(10), 1000);"); correctly defines a callback and calls it after 1 second delay. driver.executeAsyncScript("return 5 + 5;"); lacks callback, C uses executeScript (sync), D uses wrong syntax.Final Answer:
driver.executeAsyncScript("var callback = arguments[0]; setTimeout(() => callback(10), 1000);"); -> Option AQuick Check:
Callback with setTimeout = A [OK]
- Not passing or calling the callback function
- Using executeScript instead of executeAsyncScript
- Wrong Java syntax for async scripts
Object result = driver.executeAsyncScript(
"var callback = arguments[0]; setTimeout(() => callback('done'), 500);");
System.out.println(result);Solution
Step 1: Understand the async script behavior
The script waits 500ms then calls callback with 'done'. Selenium waits for this callback and returns its value.Step 2: Check what is printed
The returned value from executeAsyncScript is 'done', so System.out.println prints 'done'.Final Answer:
done -> Option CQuick Check:
Callback returns 'done' = C [OK]
- Expecting null before callback runs
- Confusing async script with synchronous
- Assuming timeout error without delay
driver.executeAsyncScript("setTimeout(() => { return 'done'; }, 1000);");Solution
Step 1: Check async script requirements
Async scripts must accept a callback argument and call it to signal completion.Step 2: Analyze the given code
The code uses setTimeout but does not accept or call any callback, so Selenium never knows when to continue.Final Answer:
Missing callback argument and not calling it to signal completion. -> Option AQuick Check:
Callback must be called = D [OK]
- Forgetting to pass callback as argument
- Returning value instead of calling callback
- Thinking arrow functions are disallowed
driver.executeAsyncScript(
"var callback = arguments[0];
var checkData = () => {
if(document.querySelector('#data').innerText !== '') {
callback('loaded');
} else {
setTimeout(checkData, 500);
}
};
checkData();
");Solution
Step 1: Understand polling in async scripts
The script repeatedly checks if '#data' element has text, calling callback only when data is loaded.Step 2: Verify callback usage and waiting
Callback is called only after data is ready, so Selenium waits properly for dynamic content.Final Answer:
This script correctly polls for data and calls callback when ready. -> Option BQuick Check:
Polling with callback = B [OK]
- Not calling callback after data loads
- Using executeScript which does not wait
- Blocking browser with infinite loops
Ready to prove it?
Pass the test and this pattern moves unknown
