DEV Community

Styrow.dev
Styrow.dev

Posted on Originally published at styrow.dev

How would you design a robust Selenium-Java test strategy to verify dynamically loaded, asynchronously appearing data in

🚨 90% of Selenium tests flake on SPAs due to async chaos. ⚠️ How do you validate dynamically loaded data with non-deterministic load orders using intelligent, stateful retries?

📌 Problem Statement
An e-commerce SPA recommendation page fetches sections via independent API calls. They render in random order.
✅ Requirements:
• All sections ("Personalized", "Trending") eventually render.
• Each section has ≥ N product cards.
• Zero duplicate product IDs across ALL sections.

💡 Solution & Code Walkthrough
Never use Thread.sleep. Build a stateful polling engine that validates data integrity, not just visibility.

public void validateSPAPage() {
    Set<String> productIds = new HashSet<>();
    List<String> targets = Arrays.asList("Personalized", "Trending");
    for (String section : targets) {
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        wait.until(ExpectedConditions.presenceOfElementLocated(
            By.xpath("//h2[contains(text(), '" + section + "')]")));
        List<WebElement> cards = driver.findElements(
            By.xpath("//h2[contains(text(), '" + section + "')]//following::article"));
        if (cards.size() < 5) throw new AssertionError("Count < 5");
        for (WebElement c : cards) {
            String id = c.getAttribute("data-id");
            if (!productIds.add(id)) throw new AssertionError("Dup: " + id);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Wrap assertions in a retry loop with exponential backoff (2s, 4s, 8s) for transient network failures.

🔑 Key Takeaways
❌ Avoid fixed waits; they break on network variance.
✅ Implement exponential backoff for transient failures.
✅ Use a Set to track product IDs for O(1) duplicate detection.
⚠️ contains(text()) is expensive on huge DOMs; prefer stable data-attributes where possible.

❓ Quick Summary Q&A
Q: Best wait strategy?
A: Poll for state (elements exist + stable), not just visibility.
Q: Handling retries?
A: Wrap assertions in a retry loop with a max attempt counter.

TAGS: selenium, java, automation, testing, spa

────────────────────────────────────────
📲 Download the App for more SDET patterns:
────────────────────────────────────────

📲 𝐅𝐑𝐄𝐄 𝐌𝐎𝐁𝐈𝐋𝐄 𝐀𝐏𝐏 — 𝟔𝟎𝟎+ 𝐒𝐃𝐄𝐓 𝐐&𝐀𝐬
Practice real-world interview scenarios offline on the free QA Automation & SDET Prep app:

🤖 𝐆𝐨𝐨𝐠𝐥𝐞 𝐏𝐥𝐚𝐲 (𝐀𝐧𝐝𝐫𝐨𝐢𝐝):
https://play.google.com/store/apps/details?id=com.app.seleniuminterviewquestions&referrer=utm_source%3Ddevto%26utm_medium%3Darticle%26utm_campaign%3Dselenium_20261006

🍎 𝐀𝐩𝐩 𝐒𝐭𝐨𝐫𝐞 (𝐢𝐎𝐒):
https://apps.apple.com/app/id6786760948?pt=128640464&ct=devto_selenium_20261006&mt=8

────────────────────────────────────────
────────────────────────────────────────

Top comments (0)