0
0
Selenium Javatesting~10 mins

Async script execution in Selenium Java - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test runs an asynchronous JavaScript script in the browser using Selenium WebDriver in Java. It verifies that the script returns the expected result within the timeout period.

Test Code - Selenium
Selenium Java
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
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();
        try {
            driver.get("https://example.com");

            JavascriptExecutor js = (JavascriptExecutor) driver;
            driver.manage().timeouts().scriptTimeout(Duration.ofSeconds(5));

            Object result = js.executeAsyncScript(
                "var callback = arguments[arguments.length - 1];"
                + "window.setTimeout(function() { callback('async result'); }, 1000);"
            );

            assert "async result".equals(result) : "Expected 'async result' but got " + result;

            System.out.println("Test Passed: Async script returned expected result.");
        } finally {
            driver.quit();
        }
    }
}
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensChrome browser window is open and ready-PASS
2Navigates to https://example.comBrowser displays the example.com homepage-PASS
3Sets script timeout to 5 secondsWebDriver configured to wait up to 5 seconds for async scripts-PASS
4Executes asynchronous JavaScript that waits 1 second then returns 'async result'Browser runs the async script and waits for callbackCheck that returned result equals 'async result'PASS
5Assertion verifies the returned result is 'async result'Test confirms the async script returned expected valueassert "async result".equals(result)PASS
6Test prints success message and closes browserBrowser closes, test ends-PASS
Failure Scenario
Failing Condition: The async script does not call the callback within 5 seconds or returns unexpected result
Execution Trace Quiz - 3 Questions
Test your understanding
What does the async script in this test do?
AImmediately returns 'async result' without delay
BWaits 1 second then returns 'async result' via callback
CWaits 5 seconds then returns 'async result'
DThrows an error instead of returning a result
Key Result
Always set an appropriate script timeout when running asynchronous JavaScript with Selenium to avoid indefinite waits and ensure timely test execution.