0
0
Selenium Javatesting~15 mins

Async script execution in Selenium Java - Build an Automation Script

Choose your learning style9 modes available
Verify asynchronous JavaScript execution on a web page
Preconditions (2)
Step 1: Open the browser and navigate to the test page URL
Step 2: Locate the button with id 'startAsync' and click it
Step 3: Use Selenium's executeAsyncScript to run a JavaScript function that waits 3 seconds and returns 'done'
Step 4: Capture the returned result from the async script execution
✅ Expected Result: The async script returns the string 'done' after approximately 3 seconds, confirming async execution works
Automation Requirements - Selenium WebDriver with Java
Assertions Needed:
Assert that the returned result from executeAsyncScript equals 'done'
Best Practices:
Use explicit waits if needed before clicking elements
Use executeAsyncScript method for asynchronous JavaScript execution
Handle possible exceptions and ensure WebDriver quits after test
Automated Solution
Selenium Java
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.

Common Mistakes - 4 Pitfalls
Using executeScript instead of executeAsyncScript for async code
Not waiting for the button to be clickable before clicking
Not casting the result of executeAsyncScript to the correct type
Not quitting the WebDriver in a finally block
Bonus Challenge

Now add data-driven testing with 3 different wait times (1000ms, 2000ms, 3000ms) and verify the async script returns 'done' each time.

Show Hint