Skip to content

Instantly share code, notes, and snippets.

@khalidabuhakmeh
Created September 18, 2024 13:26
Show Gist options
  • Save khalidabuhakmeh/f2d99c1d2ca5bd1ee1b8bdf003e0aad7 to your computer and use it in GitHub Desktop.
Save khalidabuhakmeh/f2d99c1d2ca5bd1ee1b8bdf003e0aad7 to your computer and use it in GitHub Desktop.
Htmx Extension methods for Playwright Testing
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}}');
});
"""
});
}
}
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();
// create a locator
var button = Page.Locator("text=Increment");
var body = Page.Locator("#value");
var currentCount = int.Parse(await body.TextContentAsync() ?? "-1");
// Click the get started link.
await button.ClickAsync();
await Page.WaitForHtmx();
// Expects the URL to contain intro.
await Expect(body).ToHaveTextAsync($"{currentCount+1}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment