Waiting for SPAs and AJAX
Synchronise Selenium with React, Angular and Vue: why document.readyState fails, pending-request counters, Angular testabilities, readiness flags, BiDi events.
Selenium’s built-in synchronisation was designed around a world where clicking a link loaded a new page and the browser told you when it was done. Single-page applications broke that model. After the first load, navigation is a JavaScript route change, data arrives through fetch calls, and the DOM is rebuilt by a framework on its own schedule. The browser has nothing to report: as far as it is concerned, the page finished loading minutes ago.
This is the root cause of most “works locally, flaky in CI” failures in SPA test suites. This lesson explains what each readiness signal actually means, which ones are trustworthy, and how to build a wait strategy that is both fast and stable.
Why document.readyState Is Not Enough
document.readyState moves through loading, interactive, and complete exactly once per document. In an SPA:
- The initial HTML is a nearly empty shell.
completefires as soon as the JavaScript bundle is loaded, often before the app has rendered anything meaningful. - Client-side route changes do not create a new document, so
readyStatestayscompletethroughout. A wait forcompleteafter clicking a nav link returns instantly. - Data loaded through
fetchorXMLHttpRequestafter the load event is invisible toreadyState.
driver.findElement(By.linkText("Orders")).click(); // client-side route changenew WebDriverWait(driver, Duration.ofSeconds(10)).until( d -> ((JavascriptExecutor) d).executeScript("return document.readyState").equals("complete"));// Returns immediately. The orders table is still loading.driver.findElement(By.cssSelector("#orders tbody tr")); // NoSuchElementException, sometimesdriver.find_element(By.LINK_TEXT, "Orders").click() # client-side route changeWebDriverWait(driver, 10).until( lambda d: d.execute_script("return document.readyState") == "complete")# Returns immediately. The orders table is still loading.driver.find_element(By.CSS_SELECTOR, "#orders tbody tr") # NoSuchElementException, sometimesawait driver.findElement(By.linkText('Orders')).click(); // client-side route changeawait driver.wait(async () =>(await driver.executeScript('return document.readyState')) === 'complete', 10000);// Returns immediately. The orders table is still loading.await driver.findElement(By.css('#orders tbody tr')); // NoSuchElementError, sometimesdriver.FindElement(By.LinkText("Orders")).Click(); // client-side route changenew WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until( d => ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").Equals("complete"));// Returns immediately. The orders table is still loading.driver.FindElement(By.CssSelector("#orders tbody tr")); // NoSuchElementException, sometimesreadyState is still useful for one thing: after a full navigation with driver.get() under the none page load strategy. Otherwise, Selenium already waits for it for you (see Page Load Strategy and Timeouts).
The Hierarchy of Readiness Signals
From most to least reliable:
| Signal | What it proves | Cost |
|---|---|---|
| The exact UI state the test needs (row with ID 1042 visible, button enabled) | The thing you are about to use is ready | None; write it per step |
| An app-provided readiness flag | The app itself says it is idle | Needs developer cooperation once |
| Framework testability APIs (Angular) | Framework has no pending tasks | Angular only |
| Pending network request counter | No fetch/XHR in flight | Needs a script injected before app code |
Library counters (jQuery.active) | No jQuery AJAX in flight | Only covers jQuery calls |
document.readyState | Initial document loaded | Useless after first load in SPAs |
| Fixed sleep | Nothing | Slow and still flaky |
The first row is the most important idea in this lesson. Generic “is the app idle” waits are a supplement, not a replacement. An app can be completely idle and still showing the wrong page because a request failed. A wait for the specific element or text you need catches that; a network-idle wait does not.
Warning: Never fix SPA timing with
Thread.sleep,time.sleepor equivalents. A sleep long enough for the slowest CI run wastes that time on every run, and it still fails on the day the API is slower. This is the single most common “fix” that makes a suite both slower and flakier.
Wait for the Outcome, Not the Activity
Most SPA waits should be explicit waits on the state the next step depends on. Some patterns that cover the majority of cases:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// Route change: wait for URL and for the new view's landmarkdriver.findElement(By.linkText("Orders")).click();wait.until(ExpectedConditions.urlContains("/orders"));wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("[data-testid='orders-view']")));
// Data load: wait for real rows, not the table shellwait.until(d -> !d.findElements(By.cssSelector("#orders tbody tr[data-order-id]")).isEmpty());
// Loading indicator: wait for it to go awaywait.until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector("[data-testid='spinner']")));
// Re-render after filter: wait for the old content to go staleWebElement firstRow = driver.findElement(By.cssSelector("#orders tbody tr"));driver.findElement(By.id("status-filter")).sendKeys("Paid");wait.until(ExpectedConditions.stalenessOf(firstRow));wait = WebDriverWait(driver, 10)
# Route change: wait for URL and for the new view's landmarkdriver.find_element(By.LINK_TEXT, "Orders").click()wait.until(EC.url_contains("/orders"))wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "[data-testid='orders-view']")))
# Data load: wait for real rows, not the table shellwait.until(lambda d: d.find_elements(By.CSS_SELECTOR, "#orders tbody tr[data-order-id]"))
# Loading indicator: wait for it to go awaywait.until(EC.invisibility_of_element_located((By.CSS_SELECTOR, "[data-testid='spinner']")))
# Re-render after filter: wait for the old content to go stalefirst_row = driver.find_element(By.CSS_SELECTOR, "#orders tbody tr")driver.find_element(By.ID, "status-filter").send_keys("Paid")wait.until(EC.staleness_of(first_row))// Route change: wait for URL and for the new view's landmarkawait driver.findElement(By.linkText('Orders')).click();await driver.wait(until.urlContains('/orders'), 10000);await driver.wait(until.elementLocated(By.css("[data-testid='orders-view']")), 10000);
// Data load: wait for real rows, not the table shellawait driver.wait(async () =>(await driver.findElements(By.css('#orders tbody tr[data-order-id]'))).length > 0, 10000);
// Loading indicator: wait for it to go awayawait driver.wait(async () =>(await driver.findElements(By.css("[data-testid='spinner']"))).length === 0, 10000);
// Re-render after filter: wait for the old content to go staleconst firstRow = await driver.findElement(By.css('#orders tbody tr'));await driver.findElement(By.id('status-filter')).sendKeys('Paid');await driver.wait(until.stalenessOf(firstRow), 10000);var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
// Route change: wait for URL and for the new view's landmarkdriver.FindElement(By.LinkText("Orders")).Click();wait.Until(d => d.Url.Contains("/orders"));wait.Until(d => d.FindElement(By.CssSelector("[data-testid='orders-view']")).Displayed);
// Data load: wait for real rows, not the table shellwait.Until(d => d.FindElements(By.CssSelector("#orders tbody tr[data-order-id]")).Count > 0);
// Loading indicator: wait for it to go awaywait.Until(d => d.FindElements(By.CssSelector("[data-testid='spinner']")).All(e => !e.Displayed));
// Re-render after filter: wait for the old content to go stalevar firstRow = driver.FindElement(By.CssSelector("#orders tbody tr"));driver.FindElement(By.Id("status-filter")).SendKeys("Paid");wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.StalenessOf(firstRow));The spinner pattern has a classic race: if you check before the spinner appears, it is “invisible” and the wait passes instantly. When that matters, wait for the spinner to appear (with a short timeout, ignoring failure) and then for it to disappear. The wait for spinner recipe shows the full version.
App-Provided Readiness Flags
The cleanest generic signal is one the application exposes on purpose. A few lines in the app’s HTTP layer can maintain a global counter, or set a data- attribute on the root element, that tests can read cheaply.
// In the application (for example an axios/fetch wrapper), enabled in test buildswindow.__pendingRequests = 0;export async function apiFetch(url, init) { window.__pendingRequests++; try { return await fetch(url, init); } finally { window.__pendingRequests--; document.documentElement.dataset.appIdle = String(window.__pendingRequests === 0); }}Tests then wait on the flag:
ExpectedCondition<Boolean> appIdle = d -> Boolean.TRUE.equals( ((JavascriptExecutor) d).executeScript( "return typeof window.__pendingRequests === 'number' && window.__pendingRequests === 0;"));
new WebDriverWait(driver, Duration.ofSeconds(15)).until(appIdle);def app_idle(d): return d.execute_script( "return typeof window.__pendingRequests === 'number' && window.__pendingRequests === 0;")
WebDriverWait(driver, 15).until(app_idle)async function appIdle(d) {return d.executeScript( "return typeof window.__pendingRequests === 'number' && window.__pendingRequests === 0;");}
await driver.wait(() => appIdle(driver), 15000);bool AppIdle(IWebDriver d) => (bool)((IJavaScriptExecutor)d).ExecuteScript( "return typeof window.__pendingRequests === 'number' && window.__pendingRequests === 0;");
new WebDriverWait(driver, TimeSpan.FromSeconds(15)).Until(AppIdle);The typeof check matters: before the app’s code runs, the counter is undefined, and treating “not yet initialised” as idle reintroduces the race. Richer apps expose more than network state, for example window.__appReady = true once the router, auth and feature flags have all resolved. The more the flag reflects “the user can interact now”, the more useful it is.
Angular: Testabilities
Angular (2 and later) registers testability objects that report whether the zone has pending macrotasks such as HTTP calls and timers. Protractor used this, and you can too.
String angularStable = "if (!window.getAllAngularTestabilities) { return true; }" + "return window.getAllAngularTestabilities().every(t => t.isStable());";
new WebDriverWait(driver, Duration.ofSeconds(15)).until( d -> (Boolean) ((JavascriptExecutor) d).executeScript(angularStable));ANGULAR_STABLE = """if (!window.getAllAngularTestabilities) { return true; }return window.getAllAngularTestabilities().every(t => t.isStable());"""WebDriverWait(driver, 15).until(lambda d: d.execute_script(ANGULAR_STABLE))const ANGULAR_STABLE ='if (!window.getAllAngularTestabilities) { return true; }' +'return window.getAllAngularTestabilities().every(t => t.isStable());';
await driver.wait(() => driver.executeScript(ANGULAR_STABLE), 15000);const string AngularStable = "if (!window.getAllAngularTestabilities) { return true; }" + "return window.getAllAngularTestabilities().every(t => t.isStable());";
new WebDriverWait(driver, TimeSpan.FromSeconds(15)).Until( d => (bool)((IJavaScriptExecutor)d).ExecuteScript(AngularStable));Caveats you need to know:
- Long-lived timers and polling make Angular never stable. A
setIntervalfor a clock, a websocket heartbeat, or RxJSintervalinside the zone keeps a macrotask pending forever. Developers can move these outside the zone withNgZone.runOutsideAngular; until then, this wait times out. - Zoneless Angular. Newer Angular versions support running without zone.js. In zoneless apps the testability API may not reflect pending work the way it used to. Check with your developers which mode the app uses before relying on it.
- AngularJS (1.x) is different: you would query the
$httpservice’spendingRequeststhrough the injector. AngularJS has been end-of-life since 2022; if you still test one, wrap that check in the same helper. - Returning
truewhen the API is missing keeps the helper safe on non-Angular pages, but it also hides a misconfiguration. Log a warning in that branch.
jQuery.active
Older apps and many server-rendered sites with jQuery sprinkles track in-flight AJAX in jQuery.active:
return window.jQuery ? window.jQuery.active === 0 : true;It only counts requests made through jQuery’s $.ajax family. A page that mixes jQuery with fetch (very common in partially modernised apps) reports idle while fetch calls are still running. Use it as one input, never as the whole answer.
A Pending-Request Counter Without App Changes
If you cannot change the application, you can install a counter yourself by wrapping fetch and XMLHttpRequest. The critical detail is when you install it. Injecting it with executeScript after the page has loaded misses every request already in flight, and is wiped on every full navigation. It needs to run before any application script, on every new document.
A preload script does exactly that. With WebDriver BiDi, script.addPreloadScript registers a function that runs in every new document before page scripts.
// pending-requests.js: the preload script body() => { let pending = 0; Object.defineProperty(window, '__pendingRequests', { get: () => pending });
const origFetch = window.fetch; window.fetch = function (...args) { pending++; return origFetch.apply(this, args).finally(() => { pending--; }); };
const origSend = XMLHttpRequest.prototype.send; XMLHttpRequest.prototype.send = function (...args) { pending++; this.addEventListener('loadend', () => { pending--; }, { once: true }); return origSend.apply(this, args); };}// BiDi preload script (requires options.enableBiDi())String preload = Files.readString(Path.of("src/test/resources/pending-requests.js"));try (Script script = new Script(driver)) { script.addPreloadScript(preload);}
driver.get("https://app.example.com");new WebDriverWait(driver, Duration.ofSeconds(15)).until(d -> Long.valueOf(0).equals( ((JavascriptExecutor) d).executeScript("return window.__pendingRequests;")));# Chromium: CDP equivalent of a preload script.# The source must run immediately, so wrap the arrow function in an IIFE.with open("tests/resources/pending-requests.js") as f: body = f.read()driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {"source": f"({body})();"})
driver.get("https://app.example.com")WebDriverWait(driver, 15).until( lambda d: d.execute_script("return window.__pendingRequests;") == 0)// BiDi preload script (build the driver with BiDi enabled: 'webSocketUrl': true)const ScriptManager = require('selenium-webdriver/bidi/scriptManager');const fs = require('fs');
const handle = await driver.getWindowHandle();const manager = await ScriptManager(handle, driver);await manager.addPreloadScript(fs.readFileSync('test/resources/pending-requests.js', 'utf8'));
await driver.get('https://app.example.com');await driver.wait(async () =>(await driver.executeScript('return window.__pendingRequests;')) === 0, 15000);// Chromium: CDP equivalent of a preload script.var body = File.ReadAllText("Resources/pending-requests.js");((ChromiumDriver)driver).ExecuteCdpCommand("Page.addScriptToEvaluateOnNewDocument", new Dictionary<string, object> { ["source"] = $"({body})();" });
driver.Navigate().GoToUrl("https://app.example.com");new WebDriverWait(driver, TimeSpan.FromSeconds(15)).Until(d => Convert.ToInt64(((IJavaScriptExecutor)d).ExecuteScript("return window.__pendingRequests;")) == 0);The Python and C# examples use the Chromium-only CDP command because it is a stable, well-known call in those bindings; both bindings also have BiDi script support, and moving to a BiDi preload script there is the cross-browser option as the API settles. See WebDriver BiDi for the current state per language.
Network-idle has its own traps
- Zero pending requests can be momentary. Clicking a button may finish one request and start the next a few milliseconds later. A robust version requires the counter to stay at zero for a short quiet window (for example 300-500 ms) before declaring idle.
- Long-polling, websockets, server-sent events and analytics beacons never finish. Exclude them by URL in the wrapper, or the counter never reaches zero.
- Idle is not rendered. The response may have arrived, but the framework renders it on the next frame. Always follow a network-idle wait with an outcome wait for the element you need.
BiDi Network Events as Signals
WebDriver BiDi lets the test itself observe network traffic from outside the page, without injecting anything. Subscribing to “request sent” and “response completed” events lets you wait for a specific request to finish, which is usually more precise than global idle.
// Requires options.enableBiDi()CompletableFuture<ResponseDetails> ordersLoaded = new CompletableFuture<>();
try (Network network = new Network(driver)) { network.onResponseCompleted(response -> { if (response.getRequest().getUrl().contains("/api/orders")) { ordersLoaded.complete(response); } });
driver.findElement(By.linkText("Orders")).click(); ResponseDetails details = ordersLoaded.get(10, TimeUnit.SECONDS); assertEquals(200, details.getResponseData().getStatus());}
// The response has arrived; now wait for it to be renderednew WebDriverWait(driver, Duration.ofSeconds(5)) .until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("tr[data-order-id]")));The same events are available in the other bindings’ BiDi network modules (JavaScript’s selenium-webdriver/bidi/network, Python’s driver.network, and .NET’s BiDi network module), but the method names differ and have changed across 4.x releases, so check your binding’s current documentation rather than translating the Java example literally. The BiDi network interception lesson covers the APIs in more depth.
Event-based waits are especially good for:
- Asserting that a click actually triggered the expected API call (and with the right payload).
- Waiting for a background save to complete before navigating away.
- Diagnosing flaky waits: log every request and response with timestamps and you can see exactly what was still in flight when the test failed.
Tip: Register the listener before the action that triggers the request. Registering after the click means a fast response can complete before you are listening, and the future never completes.
Putting It Together: A Layered Wait Helper
A practical SPA helper combines a cheap generic check with the specific condition each step needs:
public class SpaWaits { private final WebDriver driver; private final WebDriverWait wait;
public SpaWaits(WebDriver driver) { this.driver = driver; this.wait = new WebDriverWait(driver, Duration.ofSeconds(15)); }
public void forAppIdle() { wait.until(d -> Boolean.TRUE.equals(((JavascriptExecutor) d).executeScript( "const net = typeof window.__pendingRequests !== 'number' || window.__pendingRequests === 0;" + "const ng = !window.getAllAngularTestabilities ||" + " window.getAllAngularTestabilities().every(t => t.isStable());" + "const jq = !window.jQuery || window.jQuery.active === 0;" + "return net && ng && jq;"))); }
public WebElement forVisible(By locator) { forAppIdle(); return wait.until(ExpectedConditions.visibilityOfElementLocated(locator)); }}class SpaWaits: IDLE_JS = """ const net = typeof window.__pendingRequests !== 'number' || window.__pendingRequests === 0; const ng = !window.getAllAngularTestabilities || window.getAllAngularTestabilities().every(t => t.isStable()); const jq = !window.jQuery || window.jQuery.active === 0; return net && ng && jq; """
def __init__(self, driver, timeout=15): self.driver = driver self.wait = WebDriverWait(driver, timeout)
def for_app_idle(self): self.wait.until(lambda d: d.execute_script(self.IDLE_JS))
def for_visible(self, locator): self.for_app_idle() return self.wait.until(EC.visibility_of_element_located(locator))const IDLE_JS ="const net = typeof window.__pendingRequests !== 'number' || window.__pendingRequests === 0;" +'const ng = !window.getAllAngularTestabilities ||' +' window.getAllAngularTestabilities().every(t => t.isStable());' +'const jq = !window.jQuery || window.jQuery.active === 0;' +'return net && ng && jq;';
class SpaWaits {constructor(driver, timeout = 15000) { this.driver = driver; this.timeout = timeout;}
async forAppIdle() { await this.driver.wait(() => this.driver.executeScript(IDLE_JS), this.timeout);}
async forVisible(locator) { await this.forAppIdle(); const el = await this.driver.wait(until.elementLocated(locator), this.timeout); await this.driver.wait(until.elementIsVisible(el), this.timeout); return el;}}public class SpaWaits{ private const string IdleJs = "const net = typeof window.__pendingRequests !== 'number' || window.__pendingRequests === 0;" + "const ng = !window.getAllAngularTestabilities ||" + " window.getAllAngularTestabilities().every(t => t.isStable());" + "const jq = !window.jQuery || window.jQuery.active === 0;" + "return net && ng && jq;";
private readonly WebDriverWait _wait;
public SpaWaits(IWebDriver driver) => _wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
public void ForAppIdle() => _wait.Until(d => (bool)((IJavaScriptExecutor)d).ExecuteScript(IdleJs));
public IWebElement ForVisible(By locator) { ForAppIdle(); return _wait.Until(d => { var el = d.FindElement(locator); return el.Displayed ? el : null; }); }}Use forAppIdle sparingly, at transitions (after login, after route changes, before taking a screenshot for visual comparison). Calling it before every single element lookup adds a round trip per action and, if any background polling sneaks in, turns into a suite-wide timeout.
Common Pitfalls
| Symptom | Cause | Fix |
|---|---|---|
| Wait returns instantly after a nav click | Waiting on readyState after a client-side route change | Wait for URL plus a view landmark |
| Spinner wait passes, element still missing | Checked before the spinner appeared | Wait for appear-then-disappear, or wait for the outcome |
| Angular stability wait always times out | Polling or intervals inside the zone | Ask devs to run them outside the zone; use outcome waits |
| Network counter never hits zero | Long-polling, websockets, analytics | Exclude those URLs in the wrapper |
| Counter misses early requests | Injected with executeScript after load | Use a preload script |
| Idle detected but element not rendered yet | Render happens after the response | Follow idle with an element-specific wait |
| TimeoutException with no clue why | Generic idle wait hides the cause | Log pending requests (BiDi) on timeout |
Summary
document.readyStateonly describes the first document load; it says nothing about SPA route changes or AJAX.- The most reliable wait is for the exact state the next step needs.
- App-provided readiness flags are the best generic signal; ask for them.
- Angular testabilities and
jQuery.activeare useful but partial. - Install request counters with a preload script so they see every request.
- BiDi network events let you wait for specific API calls and diagnose flaky waits from outside the page.
Finished this lesson?
Mark it complete to track your progress through the course. Saved in this browser only.