About Waiting For HTMX to Be Applied in Playwright Tests

Waiting for a load event in Playwright doesn't guarantee that HTMX has been applied when you want to trigger a click on a dynamic element. Here's how to wait for the HTMX to be applied to a DOM element:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from django.urls import reverse
from playwright.sync_api import sync_playwright

def wait_for_htmx_applied(page, selector):
    page.wait_for_function(
        """
            selector => {
                const el = document.querySelectorAll(selector)[0];
                return el && el['htmx-internal-data'] !== null;
            }
        """,
        arg=selector,
    )
    return page.locator(selector).all()[0]

playwright = sync_playwright().start()
browser = playwright.chromium.launch(headless=False)
context = browser.new_context(viewport={"width": 1200, "height": 800})
page = context.new_page()

page.goto("https://example.com/")

path = reverse("htmx_more_info")
wait_for_htmx_applied(page, f'[data-htmx-get="{path}"]').click()

browser.close()
playwright.stop()

DOM elements with data-hx-* or hx-* attributes get the htmx-internal-data property when htmx event handling is applied to them. That's how we can recognize that in Playwright tests.

Tips and Tricks Programming Testing Django 5.x Django 4.2 Django 3.2 htmx Playwright