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.
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.
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(); } } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and Chrome browser opens | Chrome browser window is open and ready | - | PASS |
| 2 | Navigates to https://example.com | Browser displays the example.com homepage | - | PASS |
| 3 | Sets script timeout to 5 seconds | WebDriver configured to wait up to 5 seconds for async scripts | - | PASS |
| 4 | Executes asynchronous JavaScript that waits 1 second then returns 'async result' | Browser runs the async script and waits for callback | Check that returned result equals 'async result' | PASS |
| 5 | Assertion verifies the returned result is 'async result' | Test confirms the async script returned expected value | assert "async result".equals(result) | PASS |
| 6 | Test prints success message and closes browser | Browser closes, test ends | - | PASS |