archive2022

Stop using Thread.Sleep: fixing flaky Selenium tests with dynamic waits in C#

Why fixed sleeps make UI tests on a Power Apps portal both slow and flaky, and how to replace them with WebDriverWait, small custom conditions and a reusable wait helper in Selenium 4 for .NET.

10 min read#dev#testing#selenium#csharp

At work I spend a lot of time on the UI test suite for the portal project. The portal is built on Dynamics 365 (Power Apps portals), and the tests are C# with Selenium WebDriver. When I started, the suite had many Thread.Sleep calls. Most of my work on flaky tests in the last months was removing them. I am writing down what we replaced them with, because I will need it again.

The code here is for Selenium 4.3 (the current .NET release) and NUnit 3, but the wait parts do not depend on the test framework.

Why fixed sleeps fail on this kind of portal

A Power Apps portal page does not load in one step. The server sends the page, then a lot happens in the browser:

  • Entity lists and some form parts load their data with AJAX after the page is “loaded”.
  • The portal shows a spinner or a loading overlay while it waits for data.
  • Some forms do partial postbacks. The page does not reload, but a part of the DOM is replaced, and the elements you found before are now stale.
  • Lookups and dropdowns fill in only after another field changes.

A Thread.Sleep(3000) guesses how long all this takes. When the test environment is fast, the test waits three seconds for nothing. When the environment is slow (a deployment just happened, or many people are testing at the same time), three seconds is not enough and the test fails. So the sleep makes the suite slower and more flaky at the same time. People then increase the sleep to 5 seconds, then 10, and the suite gets slower every month.

A dynamic wait checks a condition again and again, and continues as soon as the condition is true. On a fast day it continues after a few hundred milliseconds. On a slow day it waits longer, up to a timeout you choose.

Implicit and explicit waits, and why not to mix them

Selenium has two kinds of waits.

An implicit wait is a driver setting. Every FindElement call keeps trying until the element exists or the time is over:

driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);

It only helps with “element is not in the DOM yet”. It does not help with “element is there but hidden behind a spinner”, “button is disabled” or “the list still shows old data”. It also makes every negative check slow: if you check that an error message is not shown, FindElements waits the full 10 seconds before it returns an empty list.

An explicit wait is a WebDriverWait with a condition, used at one place in the test. You decide what to wait for.

The Selenium documentation says not to mix them, and I agree after seeing it go wrong. When an implicit wait is set, each FindElement inside your explicit wait condition can block for the implicit timeout. The explicit wait then cannot poll at its own interval, and the total wait time becomes hard to predict. We had tests that “timed out after 20 seconds” but actually ran for much longer.

What we do now: implicit wait is zero, always, and every wait is explicit.

driver.Manage().Timeouts().ImplicitWait = TimeSpan.Zero;

WebDriverWait with a lambda

WebDriverWait is in the OpenQA.Selenium.Support.UI namespace. I install both Selenium.WebDriver and Selenium.Support from NuGet and keep them on the same version.

Until takes a function from IWebDriver to some result. It calls the function every PollingInterval until the result is not null and not false, then returns it. If the timeout is reached, it throws WebDriverTimeoutException.

using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;

var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20))
{
    PollingInterval = TimeSpan.FromMilliseconds(250)
};

IWebElement saveButton = wait.Until(d =>
{
    var el = d.FindElement(By.Id("SaveButton"));
    return el.Displayed && el.Enabled ? el : null;
});
saveButton.Click();

If FindElement throws NoSuchElementException inside the lambda, WebDriverWait already ignores it and tries again. Other exceptions stop the wait unless you tell it to ignore them (see below).

What happened to ExpectedConditions

Many examples online use ExpectedConditions.ElementToBeClickable(...). In the .NET bindings this class was marked obsolete in Selenium 3.11, and removed in Selenium 4 (the .NET changelog for 4.0.0-alpha1 says “Removed deprecated ExpectedConditions and PageFactory classes”). So with Selenium 4 that code does not compile.

The old implementation lives on in a separate community package, DotNetSeleniumExtras.WaitHelpers. The namespace is SeleniumExtras.WaitHelpers:

using SeleniumExtras.WaitHelpers;

var button = wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("SaveButton")));

It works with Selenium 4. But the package has not had a release since 2018, and the conditions are only a few lines each. I used it for a short time during the migration and then replaced it with our own lambdas. Then I can see exactly what each condition checks, and I can add the portal-specific checks the package does not know about.

Custom conditions for the portal

These are the conditions that removed most of our sleeps.

Document ready

After a full navigation, wait for the browser to finish loading the page:

wait.Until(d =>
    ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").Equals("complete"));

This is not enough on its own, because the portal loads a lot after readyState is complete. But it is a cheap first step.

No AJAX request and no partial postback running

The portal pages use jQuery, and the classic Web Forms pages use ASP.NET AJAX for partial postbacks. Both can tell you if they are busy. The script checks if each library exists first, so it is safe on pages that do not use them:

const string IdleScript = @"
    if (window.jQuery && window.jQuery.active > 0) { return false; }
    if (window.Sys && Sys.WebForms && Sys.WebForms.PageRequestManager) {
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        if (prm.get_isInAsyncPostBack()) { return false; }
    }
    return true;";

wait.Until(d => (bool)((IJavaScriptExecutor)d).ExecuteScript(IdleScript));

jQuery.active only counts requests made through jQuery. Requests made with fetch are not counted. On our pages that was fine, but check yours in the browser console before you trust it.

Loading overlay gone

The portal shows a spinner while an entity list loads, and a modal form shows its own loading layer. Check your own page in the browser dev tools to find the right selector. The class names below are only examples:

var overlay = By.CssSelector(".entitylist-loading, .modal-loading");

wait.Until(d => d.FindElements(overlay).All(e => !e.Displayed));

FindElements returns an empty list when nothing matches, so this is true when the overlay is removed and also when it is only hidden. This one condition fixed more flaky tests than anything else. Before it, tests clicked on a row while the spinner was still on top, and the click went to the overlay.

Element clickable

Displayed && Enabled is what the old ElementToBeClickable checked. It does not know about overlays. When something still covers the element, Click() throws ElementClickInterceptedException. I handle that by doing the click inside the wait and ignoring that exception, so the wait just tries again:

wait.IgnoreExceptionTypes(typeof(ElementClickInterceptedException));
wait.Until(d =>
{
    var el = d.FindElement(By.Id("SubmitButton"));
    if (!el.Displayed || !el.Enabled) { return false; }
    el.Click();
    return true;
});

Be careful with this for buttons that are not safe to click twice. If the first click worked but threw anyway (it is rare, but I have seen it with slow pages), you submit twice. For submit buttons I prefer to wait for the overlay to be gone first, then click once.

StaleElementReferenceException

After a partial postback, the part of the page you found earlier is replaced. Any IWebElement you hold for it is now stale, and using it throws StaleElementReferenceException.

Two rules helped:

  1. Do not keep IWebElement objects across steps. Keep the By locator and find the element again inside the wait condition.
  2. Tell the wait to ignore stale elements, so a condition that runs during the DOM replacement simply tries again:
wait.IgnoreExceptionTypes(
    typeof(NoSuchElementException),
    typeof(StaleElementReferenceException));

Rule 1 matters more. Ignoring the exception does not help if the lambda uses an element that was found outside of it, because that element stays stale forever and the wait just times out.

A small reusable helper

We ended with one small class that every page object uses. The important part is that every wait has a description. It goes into the timeout message and into the log.

using System;
using System.Diagnostics;
using System.Linq;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;

public class Waits
{
    private readonly IWebDriver _driver;
    private readonly TimeSpan _timeout;

    private const string IdleScript = @"
        if (window.jQuery && window.jQuery.active > 0) { return false; }
        if (window.Sys && Sys.WebForms && Sys.WebForms.PageRequestManager) {
            if (Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) { return false; }
        }
        return document.readyState === 'complete';";

    private static readonly By Overlay = By.CssSelector(".entitylist-loading, .modal-loading");

    public Waits(IWebDriver driver, TimeSpan? timeout = null)
    {
        _driver = driver;
        _timeout = timeout ?? TimeSpan.FromSeconds(30);
    }

    public T Until<T>(Func<IWebDriver, T> condition, string what, params Type[] alsoIgnore)
    {
        var wait = new WebDriverWait(_driver, _timeout)
        {
            PollingInterval = TimeSpan.FromMilliseconds(250),
            Message = $"waiting for {what}"
        };
        wait.IgnoreExceptionTypes(
            new[] { typeof(NoSuchElementException), typeof(StaleElementReferenceException) }
                .Concat(alsoIgnore).ToArray());

        var sw = Stopwatch.StartNew();
        try
        {
            T result = wait.Until(condition);
            Log($"ok after {sw.ElapsedMilliseconds} ms: {what}");
            return result;
        }
        catch (WebDriverTimeoutException)
        {
            Log($"TIMEOUT after {sw.ElapsedMilliseconds} ms: {what} (url: {_driver.Url})");
            throw;
        }
    }

    public void PageIdle() =>
        Until(d => (bool)((IJavaScriptExecutor)d).ExecuteScript(IdleScript), "page idle (no AJAX, no postback)");

    public void OverlayGone() =>
        Until(d => d.FindElements(Overlay).All(e => !e.Displayed), "loading overlay to disappear");

    public IWebElement Visible(By locator) =>
        Until(d =>
        {
            var el = d.FindElement(locator);
            return el.Displayed ? el : null;
        }, $"{locator} to be visible");

    public void Click(By locator)
    {
        PageIdle();
        OverlayGone();
        Until(d =>
        {
            var el = d.FindElement(locator);
            if (!el.Displayed || !el.Enabled) { return false; }
            el.Click();
            return true;
        }, $"click on {locator}", typeof(ElementClickInterceptedException));
    }

    private static void Log(string message) =>
        Console.WriteLine($"[wait] {DateTime.Now:HH:mm:ss.fff} {message}");
}

A page object then looks like this:

public void SubmitApplication()
{
    _waits.Click(By.Id("SubmitButton"));
    _waits.PageIdle();
    _waits.Visible(By.CssSelector(".alert-success"));
}

I left Console.WriteLine here to keep the class independent. With NUnit, the console output is attached to the test result, so it shows up next to the failure. Use your logger if you have one.

One thing I did not solve well: the timeout. A single 30 second default is too long for most steps and too short for a few slow ones, such as a large list with filters. For those, the page object creates a Waits with a longer timeout and a comment explaining why. I prefer that to raising the default for everything.

Telling a real timeout from a flaky one

After the sleeps were gone, failures were fewer, but each failure still needed a person to look at it. The description in each wait made this much faster. A failure now says something like TIMEOUT after 30012 ms: loading overlay to disappear (url: ...) and not only “element not found”.

How I read them:

  • Timeout while waiting for the overlay or for “page idle”. The page was still busy. Often the environment was slow or a backend call failed. Look at the screenshot: if the spinner is still there, rerun first and check the environment. If it happens on the same page many times, talk to the developers, because a request may hang.
  • Timeout waiting for an element, page idle, no overlay. The page finished and the element is not there. This is usually a real problem: a changed ID, a form that now has a different layout, a business rule that hides the field, or a real bug.
  • Stale element errors that escape the wait. Almost always a test bug. Some code holds an IWebElement across a postback.

The “ok after N ms” lines are also useful. When a wait that used to take half a second slowly moves to 10 or 15 seconds over a few weeks, the test still passes, but it will start to time out on a bad day. I now look at those numbers before I raise any timeout.

Some flaky tests stayed flaky after all this. In most of those cases, two tests changed the same test record. That is a test data problem, and no wait fixes it.