skip to content
Khalid Abuhakmeh logo Khalid Abuhakmeh

HTMX vs Playwright: How to Test HTMX Apps with Playwright in C#

HTMX and Playwright aren't rivals: HTMX builds the UI, Playwright tests it. Wait for htmx:afterSettle in C# tests instead of guessing timeouts.

5 min read Updated

Community member Jonathan Channon recently approached me about an appropriate way to test your Htmx-powered applications using the Playwright testing framework. It can be annoying to time it right between sending an HTMX request, processing it on the server, and applying it to the page.

In this post, we’ll show a surefire way to wait for HTMX to finish before testing your page state, leading to more reliable tests and faster execution. Let’s go.

Updated November 2026 with a race-free wait helper and answers to common HTMX and Playwright questions.

HTMX vs Playwright: what’s the difference?

HTMX and Playwright aren’t alternatives, so you don’t pick one over the other. HTMX is a small JavaScript library that lets HTML elements send requests and swap server-rendered HTML into the page. Playwright is a browser automation framework from Microsoft for end-to-end testing. You build the UI with HTMX and test it with Playwright.

HTMX Playwright
What it is Front-end hypermedia library Browser automation and testing framework
Runs in Your users’ browsers, as part of your app Your test suite or CI pipeline
Used for Partial page updates via hx-get, hx-post, hx-swap Clicking, typing, and asserting against real browsers
C# angle Pairs with ASP.NET Core partials and Razor Pages Microsoft.Playwright NuGet package with NUnit, MSTest, or xUnit

The tricky part of using them together is timing. HTMX updates the page asynchronously, so a Playwright test has to know when HTMX is done before it asserts anything. The rest of this post solves that. If you’re new to HTMX, start with my guide to HTMX with ASP.NET Core. For a general Playwright setup, see end-to-end testing with ASP.NET Core, xUnit, and Playwright.

The Htmx Counter Application

Let’s first see what application we’ll be testing. It’s a simple **Counter ** component that increases in value when the user presses a button.

@model HtmxPlaywrightIntegration.ViewModels.CounterViewModel
<div id="counter" class="card">
<div id="value" class="card-body">
@Model.Count
</div>
<div class="card-footer">
<form asp-page="Index" method="post"
hx-post
hx-target="#counter"
hx-swap="outerHTML">
<button class="btn btn-primary">Increment</button>
</form>
</div>
</div>

The ASP.NET Core endpoint is straightforward.

using HtmxPlaywrightIntegration.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace HtmxPlaywrightIntegration.Pages;
public class IndexModel(ILogger<IndexModel> logger) : PageModel
{
public static CounterViewModel Value { get; set; }
= new();
public void OnGet()
{
}
public IActionResult OnPost()
{
Value.Count += 1;
return Partial("_Counter", Value);
}
}

Clicking the button will make a request to the server, increment the value, and return the HTML snippet to be processed into the page.

Now, let’s move on to the next part of the process, the Htmx lifecycle.

Htmx Request Lifecycle Events

Htmx contains multiple lifecycle events that we can utilize during a request. These events allow us to modify outgoing requests and understand what stages Htmx is at during the processing phase.

The lifecycle event we are most interested in is htmx:afterSettle. Settling is the process after all DOM changes have been applied and the page is now stable. Let’s hook into this page event and write a console message. I’ve added this to the typical site.js file, but it can go anywhere within your application.

document.body.addEventListener('htmx:afterSettle', function(evt) {
console.log('playwright:continue');
});

Now, whenever we settle the page, a console message will be written with the value of playwright:continue. We’ll see how to register this script into our page in the next section using the Playwright APIs.

Playwright and Htmx Extensions

Now, let’s look at our test.

namespace HtmxPlaywrightIntegration.Tests;
[Parallelizable(ParallelScope.Self)]
[TestFixture]
public class Tests : PageTest
{
[Test]
public async Task CanIncrementCountUsingHtmx()
{
await Page.GotoAsync("http://localhost:5170");
await Page.RegisterHtmxLifecycleListener();
var button = Page.Locator("text=Increment");
var body = Page.Locator("#value");
var currentCount = int.Parse(await body.TextContentAsync() ?? "-1");
await button.ClickAsync();
await Page.WaitForHtmx();
await Expect(body).ToHaveTextAsync($"{currentCount+1}");
}
}

We first call the RegisterHtmxLifecycleListener script. This is the same JavaScript seen above. Then, we call WaitForHtmx, which will wait for the console message in our page’s output. Let’s see how these extension methods work.

using Microsoft.Playwright;
namespace HtmxPlaywrightIntegration.Tests;
public static class HtmxExtensions
{
private const string Continue = "playwright:continue";
public static Task WaitForHtmx(this IPage page)
{
return page.WaitForConsoleMessageAsync(new() {
Predicate = message => message.Text == Continue
});
}
public static Task RegisterHtmxLifecycleListener(this IPage page)
{
return page.AddScriptTagAsync(new()
{
// language=javascript
Content = $$"""
document.body.addEventListener('htmx:afterSettle', function(evt) {
console.log('{{Continue}}');
});
"""
});
}
}

It’s that easy. Now your Playwright tests can wait for messages generated by the Htmx lifecycle, so you don’t have to worry about front-end or back-end changes affecting how your tests run. Additionally, you won’t have to waste time waiting for random delays to progress through your tests.

A race-free variant

Calling WaitForHtmx after ClickAsync works in practice, but there’s a small window where a very fast response could settle before the test starts listening. Playwright’s RunAndWaitForConsoleMessageAsync closes that gap: it starts listening first, then runs your action.

public static Task WaitForHtmxAfter(this IPage page, Func<Task> action)
{
return page.RunAndWaitForConsoleMessageAsync(action, new() {
Predicate = message => message.Text == Continue
});
}

The test then becomes a single call:

await Page.WaitForHtmxAfter(() => button.ClickAsync());
await Expect(body).ToHaveTextAsync($"{currentCount + 1}");

Frequently asked questions

Is Playwright a replacement for HTMX?

No. Playwright never ships to your users. It drives a browser from your tests. HTMX is part of your app’s front end. Most HTMX projects that want end-to-end tests use Playwright, Selenium, or Cypress to exercise the HTMX behavior.

Why are my Playwright tests flaky with HTMX?

The test usually asserts before HTMX has swapped in the new HTML. Fixed delays like Task.Delay or WaitForTimeoutAsync either waste time or aren’t long enough. Waiting for the htmx:afterSettle event, as shown above, ties the test to the moment the DOM is stable.

Doesn’t Playwright’s auto-waiting handle this already?

Partly. Web-first assertions like ToHaveTextAsync retry until they pass or time out, which covers many simple cases. Waiting for htmx:afterSettle still helps when the expected value isn’t known ahead of time, when you read values with TextContentAsync, or when you want a test to fail fast and clearly if an HTMX request never completes.

Which HTMX event should a test wait for?

Use htmx:afterSettle. It fires after HTMX has swapped the new content and finished settling, so the DOM is in its final state. htmx:afterSwap fires as soon as new content is in place but before settling finishes, and htmx:afterRequest tracks the request lifecycle rather than the DOM, so neither guarantees a stable page.

I hope you found this post helpful. Have fun building Htmx apps tested by Playwright. Cheers.

Comments

Related Posts