Testing HTMX Hypermedia Apps with Playwright

Testing HTMX Hypermedia Apps with Playwright

HTMX flips the script on modern frontend development. Instead of shipping a JavaScript SPA that fetches JSON and renders itself, you return HTML fragments from the server and let HTMX swap them into the DOM. Less JavaScript, more HTTP — and a genuinely different testing challenge.

Playwright handles it well, but you need to adjust your mental model. This guide covers everything you need to test HTMX applications reliably: request interception, partial HTML assertions, out-of-band swaps, and patterns that survive real CI environments.

Why HTMX Testing Is Different

In a React or Vue app, you test component state and JavaScript logic. In an HTMX app, the logic lives on the server. What the browser receives is HTML — and Playwright's job is to verify that the right HTML showed up in the right place after the right HTTP exchange.

The key differences:

  • No JavaScript component tree — there's nothing to inspect with page.evaluate() in the traditional sense
  • Partial page updates — a click triggers a GET or POST, and only a fragment of the DOM changes
  • Server-driven state — test failures can be server errors, not client bugs
  • HTMX attributes drive behavior — hx-get, hx-post, hx-swap, hx-target are the contracts you're testing

Understanding this shapes every testing decision below.

Setting Up Playwright for HTMX

Start with a standard Playwright install:

npm init playwright@latest

For HTMX apps, you'll want to configure request interception and response monitoring. Add this to your playwright.config.ts:

import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: {
    baseURL: 'http://localhost:3000',
    // Capture network activity for debugging
    trace: 'on-first-retry',
  },
  // HTMX apps often have slower server round-trips than SPAs
  timeout: 10000,
});

The Core Testing Pattern: Trigger → Wait → Assert

Every HTMX interaction follows the same shape: user triggers an action, HTMX makes an HTTP request, the server returns HTML, HTMX swaps it into the DOM. Your test mirrors this exactly.

import { test, expect } from '@playwright/test';

test('clicking "Load More" appends new items to the list', async ({ page }) => {
  await page.goto('/articles');

  // Verify initial state
  const items = page.locator('[data-testid="article-item"]');
  await expect(items).toHaveCount(10);

  // Trigger HTMX request
  await page.click('[hx-get="/articles/more"]');

  // Wait for HTMX swap to complete
  await expect(items).toHaveCount(20);
});

toHaveCount(20) will wait up to the configured timeout for the DOM to update. Playwright's auto-waiting is your friend here — resist the urge to add manual page.waitForTimeout() calls.

Monitoring HTMX HTTP Requests

For more precise tests, intercept the HTMX requests directly:

test('search triggers correct HTMX request', async ({ page }) => {
  await page.goto('/search');

  // Set up request monitor before triggering
  const htmxRequest = page.waitForRequest(
    req => req.url().includes('/search/results') && req.method() === 'GET'
  );

  await page.fill('[name="q"]', 'playwright testing');
  await page.keyboard.press('Enter');

  const request = await htmxRequest;
  expect(request.url()).toContain('q=playwright+testing');

  // Also verify the DOM updated
  await expect(page.locator('[data-testid="results-container"]')).not.toBeEmpty();
});

This catches cases where the request fired but had wrong parameters — a class of bug that pure DOM assertions miss.

Testing HTMX Swap Targets

HTMX's hx-target and hx-swap attributes define where and how content gets inserted. Test them explicitly:

test('form submission replaces only the form, not the whole page', async ({ page }) => {
  await page.goto('/contact');

  // Capture a reference to the element that should NOT change
  const nav = page.locator('nav');
  const navText = await nav.textContent();

  // Submit the form
  await page.fill('[name="email"]', 'test@example.com');
  await page.fill('[name="message"]', 'Hello from tests');
  await page.click('[type="submit"]');

  // Verify the swap target updated
  await expect(page.locator('[data-testid="form-container"]'))
    .toContainText('Thanks for your message');

  // Verify nothing else changed
  expect(await nav.textContent()).toBe(navText);
});

This is the test that catches accidental full-page reloads or wrong hx-target values.

Handling Out-of-Band Swaps (OOB)

HTMX's out-of-band swaps (hx-swap-oob) update multiple parts of the DOM from a single response. Testing them requires checking multiple targets:

test('adding to cart updates both cart icon and product page', async ({ page }) => {
  await page.goto('/products/widget');

  const cartCount = page.locator('[data-testid="cart-count"]');
  await expect(cartCount).toHaveText('0');

  // This triggers an OOB swap: primary target = product button, OOB = cart count
  await page.click('[hx-post="/cart/add"]');

  // Check primary target
  await expect(page.locator('[data-testid="add-to-cart-btn"]'))
    .toHaveText('Added!');

  // Check OOB swap
  await expect(cartCount).toHaveText('1');
});

Testing HTMX Indicators and Loading States

HTMX adds htmx-request class to elements during pending requests and supports hx-indicator for custom loading elements. These are worth testing in slow network conditions:

test('shows loading indicator during slow requests', async ({ page }) => {
  // Throttle the network to make the loading state visible
  await page.context().route('**/api/slow-endpoint', async route => {
    await new Promise(resolve => setTimeout(resolve, 500));
    await route.continue();
  });

  await page.goto('/dashboard');

  // Click trigger and immediately check for loading state
  const loadPromise = page.waitForResponse('**/api/slow-endpoint');
  await page.click('[hx-get="/api/slow-endpoint"]');

  // The indicator should be visible while request is pending
  await expect(page.locator('[data-testid="loading-spinner"]')).toBeVisible();

  // Wait for response and verify spinner is gone
  await loadPromise;
  await expect(page.locator('[data-testid="loading-spinner"]')).toBeHidden();
});

Mocking Server Responses with Route Interception

For unit-style tests that don't depend on a running backend, mock the server responses:

test('displays error message when server returns 500', async ({ page }) => {
  await page.route('**/submit', route => {
    route.fulfill({
      status: 500,
      contentType: 'text/html',
      body: '<div id="form-error">Something went wrong. Please try again.</div>',
    });
  });

  await page.goto('/contact');
  await page.click('[type="submit"]');

  await expect(page.locator('#form-error')).toBeVisible();
  await expect(page.locator('#form-error')).toContainText('Something went wrong');
});

HTMX's hx-swap-oob and error handling (via htmx:responseError events) are fully testable this way. You control exactly what the server returns and verify the client handles it correctly.

Testing HTMX History and Navigation

HTMX supports browser history via hx-push-url. Test that the URL updates correctly:

test('navigating to a product updates the URL', async ({ page }) => {
  await page.goto('/products');

  await page.click('[hx-get="/products/widget-pro"][hx-push-url="true"]');

  // Wait for the content swap
  await expect(page.locator('h1')).toContainText('Widget Pro');

  // Verify URL updated
  expect(page.url()).toContain('/products/widget-pro');

  // Test browser back button
  await page.goBack();
  await expect(page.locator('h1')).toContainText('Products');
});

Handling HTMX Events in Tests

HTMX fires JavaScript events at each lifecycle point (htmx:beforeRequest, htmx:afterSwap, etc.). You can listen to these for precise synchronization:

test('custom event fires after successful swap', async ({ page }) => {
  await page.goto('/dashboard');

  // Listen for the HTMX after-swap event
  const swapComplete = page.evaluate(() => {
    return new Promise(resolve => {
      document.body.addEventListener('htmx:afterSwap', (event) => {
        resolve((event as CustomEvent).detail.target.id);
      }, { once: true });
    });
  });

  await page.click('[hx-get="/api/stats"]');

  const targetId = await swapComplete;
  expect(targetId).toBe('stats-container');
});

CI Integration Patterns

HTMX apps need a running server for Playwright tests. Here's a reliable CI setup:

# .github/workflows/test.yml
name: E2E Tests
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20

      - name: Install dependencies
        run: npm ci

      - name: Install Playwright browsers
        run: npx playwright install --with-deps chromium

      - name: Start server
        run: npm run start &
        # Or use: npx wait-on http://localhost:3000

      - name: Wait for server
        run: npx wait-on http://localhost:3000

      - name: Run Playwright tests
        run: npx playwright test

      - name: Upload test artifacts
        if: failure()
        uses: actions/upload-artifact@v4
        with:
          name: playwright-report
          path: playwright-report/

For Django + HTMX, replace the Node server start with your Django dev server command.

Common HTMX Testing Pitfalls

Race conditions from missing waits — Playwright's auto-waiting handles most cases, but if you're asserting on something that isn't a DOM element (like a network request count), wait explicitly.

Testing hx-boost links — Boosted links still navigate but via HTMX. They behave like HTMX requests, not full navigations. Use page.waitForNavigation() or wait for the expected DOM state.

CSRF tokens — Server-rendered apps often use CSRF protection. HTMX handles this via hx-headers or meta tags. If your tests fail with 403s, check that your test environment has CSRF properly configured (or disabled for tests).

Testing WebSocket extensions — If you use hx-ws for real-time updates, you'll need to set up WebSocket mocking. Consider using Playwright's page.routeWebSocket() API.

Monitoring HTMX Apps in Production

Playwright tests catch regressions before deployment. For production, you need continuous monitoring — automated tests running against your live app on a schedule.

HelpMeTest runs your Playwright-style tests on a schedule and alerts you when HTMX interactions break. It handles server-side rendering, partial page updates, and the full hypermedia lifecycle — no configuration needed beyond pointing it at your app.

The same test patterns from this guide work in HelpMeTest without modification. Write tests locally with Playwright, deploy your app, and let HelpMeTest watch it 24/7.

Summary

Testing HTMX apps with Playwright comes down to a few core principles:

  1. Think in HTTP exchanges, not component state — a click triggers a request, a response updates the DOM
  2. Use Playwright's auto-waiting — toContainText(), toHaveCount(), toBeVisible() all wait automatically
  3. Monitor requests, not just the DOM — page.waitForRequest() catches parameter bugs
  4. Test swap targets explicitly — verify that only the right parts of the page changed
  5. Mock slow responses to test loading states and error handling

HTMX's server-driven model makes it easier to test than SPAs in some ways — you're just verifying HTML in the DOM, not untangling React state trees. Playwright makes that straightforward.

Read more

Start now free