Migrating from Playwright to Selenium: From Flaky Tests to Reliable Execution

Migrating a UI test suite from Playwright to Selenium involves more than changing locators and replacing method calls. The converted code can look correct and still fail intermittently during execution.

That was the main challenge in my migration. I had approximately 5,000 lines of code to convert.
After the conversion, the tests worked, but they were flaky: the same section could pass several times and then fail without any code changes.

The solution was to create reusable interaction methods that handled targeting, waiting, retries, and verification consistently. Applying these methods throughout the suite resolved the intermittent failures I was encountering and reduced many scattered sleeps.

Before explaining those methods, here are practical comparisons showing how the interactions changed.

The Selenium examples use the project’s existing abstraction over WebDriver. This is an implementation choice; the underlying principles can be applied within another test structure.

1. Clicking a dashboard button

With Playwright:

await Page
    .GetByRole(AriaRole.Button, new() { Name = "Employees" })
    .ClickAsync();

In the Selenium implementation:

Here, title contains "Employees".

var employeesWidget = cockpitPage
    .Find("cmf-core-dashboards-buttonwidget")
    .Where(new CockpitFilterOptions
    {
        HasText = title
    });

var employeesButton = employeesWidget.Find("button.cmf-btn");

await employeesButton.WaitUntilAsync(
    new CockpitWaitOptions
    {
        State = CockpitWaitState.Visible
    });

await employeesButton.ClickElementAsync();

Playwright identifies the button through its role and accessible name. The migrated implementation identifies the dashboard widget, finds its inner button, waits for visibility, and clicks it.

Tip: scope the lookup to the component containing the button when its text can appear elsewhere on the page.

2. Filling a property editor input

With Playwright:

await Page
    .Locator("cmf-core-business-controls-propertyeditor")
    .Filter(new() { HasText = "Number of Labels" })
    .Nth(0)
    .GetByRole(AriaRole.Textbox)
    .FillAsync("200");

In the Selenium implementation:

The property editor is identified through a configurable attribute:

string propertyEditorSelector =
    $"cmf-core-business-controls-propertyeditor[{attribute}='{identifier}']";

For this interaction, the configuration uses:

  • attribute: "data-label"
  • identifier: "Number Of Labels"
  • widgetName: "PrinterOptionsHUMaterial"
  • value: "200"

The widget-scoped lookup is:

cockpitPage
    .Find($"[data-widget-name='{widgetName}']")
    .Find(propertyEditorSelector)
    .Find("cmf-core-controls-input")
    .Find("input");

After assigning the lookup to inputField, the implementation waits and fills:

await inputField.WaitUntilAsync(
    new CockpitWaitOptions
    {
        State = CockpitWaitState.Visible
    });

await inputField.FillElementAsync(value);

It then verifies the value through native Selenium:

var input = driver.FindElement(
    By.CssSelector(fullInputSelector));

var actualValue = input.GetAttribute("value");

if (actualValue == value)
{
    return;
}

The original locator selected the first matching editor. The migrated implementation identifies the property within a specific widget and checks whether the requested value was entered.

Tip: prefer component identity over position. Review .First and .Nth(...) usages during migration, especially when several components contain the same label.

3. Selecting a list item

With Playwright:

await Page
    .GetByRole(AriaRole.List)
    .GetByText("Consumables")
    .ClickAsync();

In the Selenium implementation:

Here, itemName contains "Checklist".

var item = cockpitPage
    .Find("cmf-mes-resource-page-resource-perform-setup")
    .Find("cmf-core-controls-list-view")
    .Find("li.cmf-core-controls-list-view-list-item")
    .Where(new CockpitFilterOptions
    {
        HasText = "Consumables"
    });

await item.ClickElementAsync();

The lookup identifies the setup page, its list view, and the matching list item.

Tip: search within the intended list rather than searching the whole page for matching text.

4. Selecting a column-view row

With Playwright:

await Page
    .Locator("span")
    .Filter(new() { HasText = "NormalRawMaterialProduct [A]" })
    .Locator("div")
    .First
    .ClickAsync();

In the Selenium implementation:

The row title is used to construct an XPath:

string titleLiteral = ToXPathLiteral("NormalRawMaterialProduct [A]");

By locator = By.XPath(
    $"(//cmf-core-controls-columnviewrow" +
    $"[.//div[@title={titleLiteral}]])[{occurrence}]");

IWebElement row = WaitUntilClickable(
    driver,
    locator,
    timeoutSeconds);

row.Click();

ToXPathLiteral handles quotation marks in the title. WaitUntilClickable waits for the candidate to be displayed and enabled.

The occurrence parameter supports cases where matching rows are repeated.

Tip: identify the row by a meaningful attribute first. Use an occurrence only when the workflow requires distinguishing repeated matches.

5. Executing a checklist item

With Playwright:

await Page
    .Locator(
        ".selectedItem > .checklist-item > " +
        ".checklist-item-header > .execution-state-button")
    .ClickAsync();

In the Selenium implementation:

const string selector =
    ".selectedItem > " +
    ".checklist-item > " +
    ".checklist-item-header > " +
    ".execution-state-button";

await cockpitPage
    .Find(selector)
    .ClickElementAsync();

// Allow CMF/Angular to activate and render the next checklist item.
await Task.Delay(waitAfterClickMilliseconds);

The selector remains focused on the selected checklist item. The implementation also allows time after the click for the next item to activate and render.

This was important when executing several checklist items consecutively.

Tip: account for the transition caused by the action, as well as the readiness of the element being clicked.

6. Clicking an action bar button

With Playwright:

await Page
    .Locator("cmf-core-controls-actionbar")
    .GetByText("Complete Setup")
    .ClickAsync();

In the Selenium implementation:

Here, buttonId contains "Resource.CompleteSetup".

var actionButton = cockpitPage
    .Find("cmf-core-controls-actionbar")
    .Find(
        $"cmf-core-controls-actionbutton[button-id='{buttonId}']");

await actionButton.WaitUntilAsync(
    new CockpitWaitOptions
    {
        State = CockpitWaitState.Visible
    });

await actionButton.ClickElementAsync();

The migrated selector identifies the action through its button-id, rather than its displayed label.

Tip: use stable action identifiers when the application provides them.

7. Clicking a wizard footer button

With Playwright:

await Page
    .GetByRole(AriaRole.Button, new() { Name = "Complete" })
    .ClickAsync();

In the Selenium implementation:

For this interaction, actionName is "finish" and footerSelector identifies the wizard footer.

var cancelButton = cockpitPage
    .Find(footerSelector)
    .Find(
        "button[data-action='" + actionName + "']:not([hidden])");

await cancelButton.WaitUntilAsync(
    new CockpitWaitOptions
    {
        State = CockpitWaitState.Visible
    });

await cancelButton.ClickElementAsync();

The variable name cancelButton comes from the existing implementation. The actionName parameter determines which button is selected.

The same lookup supports actions such as "next", "back", and "close".

Set footerSelector according to the footer component used by the current view:

Footer component footerSelector
Execution view footer cmf-core-controls-execution-view-footer
Wizard footer cmf-core-controls-wizard-footer

The interaction code stays the same; only footerSelector changes. The actionName parameter selects the button within that footer, such as "finish", "next", "back", or "close".

Tip: scope common button actions to the appropriate footer. Different views may use different footer components.

8. Adding material to a feeder

This interaction combines opening a menu, selecting an option, entering a material, and moving focus.

With Playwright:

await Page.Locator(".icon-core-st-sm-add").ClickAsync();

Thread.Sleep(1000);

await Page
    .Locator("span")
    .Filter(new() { HasText = "New Material" })
    .First
    .ClickAsync();

Thread.Sleep(1000);

await Page.GetByPlaceholder("Material").ClickAsync();

Thread.Sleep(1000);

await Page
    .GetByPlaceholder("Material")
    .FillAsync(_executionScenario.NormalRawMaterialName);

Thread.Sleep(2000);

await Page.Keyboard.PressAsync("Tab");

Thread.Sleep(1000);

In the Selenium implementation, opening the material entry:

await cockpitPage
    .Find(".icon-core-st-sm-add")
    .ClickElementAsync();

var field1 = cockpitPage
    .Find("span")
    .Where(new CockpitFilterOptions
    {
        HasText = "New Material"
    })
    .FirstMatch;

await field1.WaitUntilAsync(
    new CockpitWaitOptions
    {
        State = CockpitWaitState.Visible
    });

await field1.ClickElementAsync();

var field2 = cockpitPage.FindByPlaceholder("Material");

await field2.WaitUntilAsync(
    new CockpitWaitOptions
    {
        State = CockpitWaitState.Visible
    });

The implementation fills the field when its value differs from the requested material:

if (!string.Equals(
    await field2.GetAttributeAsync("value"),
    materialName,
    StringComparison.Ordinal))
{
    await field2.ClickElementAsync();
    await field2.FillElementAsync(materialName);

    await Task.Delay(2000);
    await cockpitPage.Keyboard.PressKeyAsync("Tab");
}

Later, it reads the value again. If it still differs, it repeats the fill-and-Tab sequence before asserting the final value.

Tip: verify the result of a multi-step interaction. Successful typing alone does not establish that the field retained the intended value.

9. Validating a wizard error message

With Playwright:

var errorMessage = await Page
    .Locator("cmf-core-controls-wizard-result .alert-danger")
    .TextContentAsync();

Assert.IsTrue(
    errorMessage.Contains(
        "The entered quantity has more decimal places " +
        "than the maximum allowed 3."),
    "An erro message should have been displayed.");

In the Selenium implementation:

var errorMessageElement = cockpitPage
    .Find("cmf-core-controls-wizard-result .alert-danger");

await errorMessageElement.WaitUntilAsync(
    new CockpitWaitOptions
    {
        State = CockpitWaitState.Visible
    });

actualMessage = await errorMessageElement.TextContentAsync();

if (actualMessage?.Contains(expectedMessage) == true)
{
    return;
}

This check runs within an attempts loop. If the expected message never appears, the assertion reports both the expected and actual text:

Assert.Fail(
    $"Expected error message was not displayed. " +
    $"Expected: '{expectedMessage}'. " +
    $"Actual: '{actualMessage}'.");

Tip: wait for the expected content, not just the existence of its container.

The migration worked, but execution was flaky

The converted interactions were mostly correct, yet the tests were initially inconsistent. A section could pass five times and then fail without any changes.

The difficulty was often timing. An element could already be visible while the application was still updating it. A click could be intercepted, or a refresh could replace the element between locating it and interacting with it.

Playwright automatically performs several checks before a normal click, including visibility, stability, enabled state, and whether the element receives pointer events. It waits for those conditions within its configured timeout.

Selenium provides explicit waits for conditions defined by the test. However, checking visibility and enabled state does not cover every application transition or prevent an element from becoming stale immediately afterward.

The conversion therefore needed more than correct selectors. It needed consistent handling of temporary interaction failures.

The methods that resolved the flakiness

I created reusable methods in GUIUtilities for the recurring interactions:

Method Responsibility
ClickColumnViewRowItemAsync Locate a row by title and wait before clicking
ClickListViewItemAsync Locate an item within the setup list
ClickSelectedChecklistItemAsync Execute the selected item with attempts and a transition delay
ClickButton Locate a dashboard button, wait, and retry failures
AddMaterialToFeeder Perform material entry and verify its value
ClickWizardFooterButton Locate a footer action, wait, and retry failures
ClickActionBarButton Locate an action by its identifier, wait, and retry failures
FillInputAsync Fill a property input and verify its resulting value
ValidateWizardErrorMessageAsync Repeatedly check for the expected error message

These methods share a purpose, but their implementations differ. Several contain explicit attempts loops. Others use an explicit wait, delegate the interaction, or repeat part of a workflow after checking the result.

Once applied throughout the suite, these methods resolved the intermittent failures I had been encountering. The tests became consistently reliable, and many scattered sleeps could be reduced or centralized.

They also significantly reduced repeated code. Instead of duplicating element lookups, waits, clicks, and retry logic across multiple tests, each test could call a reusable method that expressed the intended action:

await GUIUtilities.ClickActionBarButton(
    Cockpit,
    "Resource.CompleteSetup",
    10);

The interaction details and recovery behavior remained inside the utility, making the tests shorter and easier to read. Future adjustments could be made in one place and applied consistently wherever the method was used.

The attempts pattern, shown once

There is no need to reproduce every method to explain the approach. This is the actual loop from ClickActionBarButton:

for (int attempt = 1; attempt <= maxAttempts; attempt++)
{
    try
    {
        var actionButton = cockpitPage
            .Find("cmf-core-controls-actionbar")
            .Find(
                $"cmf-core-controls-actionbutton[button-id='{buttonId}']");

        await actionButton.WaitUntilAsync(
            new CockpitWaitOptions
            {
                State = CockpitWaitState.Visible
            });

        await actionButton.ClickElementAsync();

        return;
    }
    catch
    {
        if (attempt == maxAttempts)
        {
            throw;
        }

        await Task.Delay(retryDelayMilliseconds);
    }
}

The structure is straightforward:

  1. Locate the element inside the attempt.
  2. Wait for visibility.
  3. Perform the interaction.
  4. Return immediately on success.
  5. On failure, wait before trying again.
  6. Propagate the exception after the final attempt.

The default configuration for this method is three attempts with two seconds between failed attempts. Tests can override those values.

Locating the element inside the loop matters because the application may have replaced it since the previous attempt. Returning immediately also means that a successful first attempt does not incur the retry delay.

ClickButton and ClickWizardFooterButton use a similar structure. Checklist execution additionally waits after success to allow the next item to render.

Verify success when an exception is not enough

Some interactions can complete without throwing and still produce the wrong result.

For that reason, FillInputAsync checks the input value after filling it. If the final attempt still contains the wrong value, it reports the mismatch:

throw new InvalidOperationException(
    $"Failed to fill input '{identifier}'. " +
    $"Expected '{value}', but input contains '{actualValue}'.");

AddMaterialToFeeder follows the same reasoning by checking the material value and repeating the entry sequence when necessary.

ValidateWizardErrorMessageAsync checks the expected text rather than treating the presence of the error container as success.

Tip: define success according to the interaction. For typing, it may be the resulting value. For validation, it is the expected message. For navigation, it is reaching the intended screen.

Reduce scattered sleeps through shared behavior

The utilities allowed the tests to stop repeating timing adjustments around every interaction.

Some fixed delays remain, particularly for checklist transitions and material entry. The practical improvement was that recurring behavior became centralized and several retry delays applied only after a failed attempt.

Where the application exposes a dependable state change, a further improvement is to wait for that condition—for example, the next checklist item becoming active or a wizard closing.

Keep attempts bounded, too. Several attempts containing long waits can make a genuine failure slow to report. After a successful submission, wait for its outcome before considering another submission.

Migration Effort and Lessons Learned

The migration involved approximately 5,000 lines of code and took roughly one to two weeks. Estimating the effort precisely in hours is difficult because the knowledge gained during the process would now make the same migration considerably faster.

At the beginning, the size of the suite made it difficult to decide where to start. I first used GitHub Copilot, but although it removed the Playwright dependencies, the result did not match my intended approach. It introduced methods that closely replicated Playwright’s behavior instead of producing the Selenium Native implementation I expected.

I used ChatGPT Plus to review that result and prepare more detailed instructions for Copilot. After reaching Copilot’s token limit, I asked ChatGPT to return the migrated files directly. That provided a useful starting point.

Running the tests exposed the flakiness. Creating the reusable interaction methods resolved those difficulties, but applying them consistently throughout the suite—and adjusting specific workflows—was the most time-consuming stage.

The syntax conversion produced working Selenium tests. Applying the reusable interaction methods made their execution reliable.

Project Reference

The migrated tests and reusable interaction methods are available in the Hollister Project.

The main files are:

  • ProductionTests.cs — the migrated production tests.
  • GUIUtilities.cs — the interaction methods used to improve reliability and reduce repeated code.

HI @Rui_Rocha
A couple of months ago, we had to perform the same migration.
Thank you for sharing this information. We will use it to confirm whether we correctly performed the migration or if there is any room to improvements on the current implementation.
Best Regards,
JoĂŁo Querido

Hi @Rui_Rocha ,

Nice blog post, and I commend you for sharing your knowledge like this, but I do have some questions regarding the suggested approach.

There are reasons we are told to use selenium and one of them is that there is a lot of tools, utilities, methods that do the heavy lifting for us.

Looking at the ColunmView example in point 4, for instance, could we not just do something like this

ColumnView = CreatePageObjects<ColumnView>(searchContext: this.RootElement).First();
ColumnView.GetRowByLabel(0,"NormalRawMaterialProduct [A]").Click();

We don’t have to wait for things to be visible or selectable. The existing tools do that for us. And should their namespaces change, like they did from version 9 to version 10 then that is also already done without need for the project teams to update the selectors in each test

It appears to me that the blog suggests to disregard all existing implementation and write all the selenium tests as if there were no utilities at hand. This certainly was the case for Playwright, which is unsupported, but not for selenium.

Hello @Johann_Knorr ,

You’re totally right! During the migration I completely forget the Page Objects the Product team has available to use :expressionless: