Server-Side Rendering Testing with HTMX

Server-Side Rendering Testing with HTMX

HTMX puts the server back in charge of rendering. Where a React app ships JSON and renders HTML in the browser, an HTMX app returns HTML fragments directly from the server. This shifts your testing strategy: the most important thing to test is what your server renders, not how JavaScript manipulates it.

This guide covers server-side rendering (SSR) testing specifically for HTMX applications — from unit-testing HTML templates to integration-testing the full hypermedia exchange.

What SSR Testing Means for HTMX

In a traditional SSR app (Rails, Django, Go templates), you test that the server returns the right HTML for a given request. HTMX adds a layer: the server now serves both full pages (on first load) and HTML fragments (on subsequent HTMX requests). Both need testing.

The test matrix for an HTMX endpoint:

Request type Expected response What to test
Full page load (browser navigation) Complete HTML document Layout, navigation, initial data
HTMX fragment request (HX-Request: true) HTML fragment only Fragment structure, data, swap target
Form submission Redirect or fragment Success/error states
Error states Error fragment or status code User-facing error messages

Testing the HTMX Request Header

HTMX sets the HX-Request: true header on all HTMX-initiated requests. Your server uses this to decide whether to return a full page or just a fragment. Test both paths:

Django example:

# views.py
def article_list(request):
    articles = Article.objects.all()
    
    if request.headers.get('HX-Request'):
        # Return only the list fragment
        return render(request, 'partials/article_list.html', {'articles': articles})
    
    # Return full page
    return render(request, 'articles/index.html', {'articles': articles})
# tests.py
from django.test import TestCase, Client

class ArticleListViewTests(TestCase):
    def setUp(self):
        self.client = Client()
        Article.objects.create(title='Test Article', slug='test-article')

    def test_full_page_load(self):
        response = self.client.get('/articles/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'articles/index.html')
        self.assertContains(response, '<html')
        self.assertContains(response, 'Test Article')

    def test_htmx_request_returns_fragment(self):
        response = self.client.get(
            '/articles/',
            HTTP_HX_REQUEST='true'
        )
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'partials/article_list.html')
        # Fragment should NOT contain full HTML document
        self.assertNotContains(response, '<html')
        self.assertContains(response, 'Test Article')

Template Unit Testing

Template rendering tests verify that your templates produce correct HTML given specific context data. They're fast, require no HTTP stack, and catch regressions in how data maps to markup.

Go template testing:

// templates_test.go
package main

import (
    "bytes"
    "html/template"
    "testing"
    "strings"
)

func TestArticleListTemplate(t *testing.T) {
    tmpl := template.Must(template.ParseFiles("templates/partials/article_list.html"))

    articles := []Article{
        {ID: 1, Title: "First Article", Slug: "first-article"},
        {ID: 2, Title: "Second Article", Slug: "second-article"},
    }

    var buf bytes.Buffer
    err := tmpl.Execute(&buf, map[string]interface{}{
        "Articles": articles,
    })

    if err != nil {
        t.Fatalf("template execution failed: %v", err)
    }

    output := buf.String()

    // Verify HTMX attributes are rendered correctly
    if !strings.Contains(output, `hx-get="/articles/1"`) {
        t.Error("expected hx-get attribute for article 1")
    }

    if !strings.Contains(output, "First Article") {
        t.Error("expected article title in output")
    }

    // Verify correct swap target is set
    if !strings.Contains(output, `hx-target="#article-detail"`) {
        t.Error("expected hx-target attribute")
    }
}

Rails RSpec view specs:

# spec/views/articles/_article_list.html.erb_spec.rb
require 'rails_helper'

RSpec.describe 'articles/_article_list', type: :view do
  let(:articles) do
    [
      build_stubbed(:article, title: 'First Article', slug: 'first-article'),
      build_stubbed(:article, title: 'Second Article', slug: 'second-article')
    ]
  end

  before { render partial: 'articles/article_list', locals: { articles: } }

  it 'renders all articles' do
    expect(rendered).to have_css('[data-testid="article-item"]', count: 2)
  end

  it 'includes correct HTMX attributes' do
    expect(rendered).to have_css(
      '[hx-get="/articles/first-article"][hx-target="#article-detail"]'
    )
  end

  it 'does not include full HTML document wrapper' do
    expect(rendered).not_to include('<html')
    expect(rendered).not_to include('<body')
  end
end

Testing HTML Fragment Structure

Your HTMX fragments need to be valid, correctly structured HTML. Beyond content testing, verify the fragment shape — the swap target expects a specific element structure:

from django.test import TestCase
from bs4 import BeautifulSoup

class ArticleFragmentTests(TestCase):
    def test_fragment_has_correct_structure(self):
        response = self.client.get(
            '/articles/',
            HTTP_HX_REQUEST='true'
        )
        
        soup = BeautifulSoup(response.content, 'html.parser')
        
        # Fragment root element must match the hx-target selector
        articles = soup.find_all(attrs={'data-testid': 'article-item'})
        self.assertGreater(len(articles), 0)
        
        # Each article item should have required HTMX attributes
        for article in articles:
            self.assertIsNotNone(
                article.get('hx-get'),
                'Article item missing hx-get attribute'
            )
            self.assertEqual(
                article.get('hx-target'),
                '#article-detail',
                'Article item has wrong hx-target'
            )

Testing Out-of-Band (OOB) Swaps in Server Responses

When your server returns OOB swaps (multiple fragments in one response), test each fragment:

class CartOOBTests(TestCase):
    def test_add_to_cart_returns_oob_cart_count(self):
        response = self.client.post(
            '/cart/add/',
            {'product_id': 1},
            HTTP_HX_REQUEST='true'
        )
        
        soup = BeautifulSoup(response.content, 'html.parser')
        
        # Primary response: product button update
        button = soup.find(attrs={'data-testid': 'add-to-cart-btn'})
        self.assertIn('Added', button.text)
        
        # OOB swap: cart count update
        oob_count = soup.find(attrs={'hx-swap-oob': True})
        self.assertIsNotNone(oob_count, 'Missing OOB swap element')
        self.assertEqual(oob_count.get('id'), 'cart-count')
        self.assertEqual(oob_count.text.strip(), '1')

Testing HTMX Response Headers

HTMX reads response headers to trigger client-side behaviors. Test that your server sends them correctly:

class HtmxHeaderTests(TestCase):
    def test_successful_form_triggers_redirect_header(self):
        """After form submit, server should send HX-Redirect"""
        response = self.client.post(
            '/contact/',
            {'email': 'test@example.com', 'message': 'Hello'},
            HTTP_HX_REQUEST='true'
        )
        
        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            response.get('HX-Redirect'),
            '/contact/thank-you/'
        )

    def test_validation_error_sends_reswap_header(self):
        """On validation error, reswap the form with errors"""
        response = self.client.post(
            '/contact/',
            {'email': 'not-an-email'},
            HTTP_HX_REQUEST='true'
        )
        
        self.assertEqual(response.status_code, 422)  # or 200 depending on your approach
        soup = BeautifulSoup(response.content, 'html.parser')
        errors = soup.find_all(class_='form-error')
        self.assertGreater(len(errors), 0)

Common HTMX response headers to test:

  • HX-Redirect — triggers client-side redirect
  • HX-Refresh — triggers full page refresh
  • HX-Trigger — fires client-side events
  • HX-Push-Url — updates browser history
  • HX-Retarget — changes the swap target dynamically

Integration Testing: Full HTMX Request Cycle

After unit-testing templates and views, test the full request cycle with an in-process HTTP client:

# spec/requests/articles_spec.rb
require 'rails_helper'

RSpec.describe 'Articles HTMX flow', type: :request do
  let!(:articles) { create_list(:article, 3) }

  describe 'GET /articles' do
    context 'regular browser request' do
      it 'returns full page' do
        get articles_path
        expect(response).to have_http_status(:ok)
        expect(response.body).to include('<html')
        expect(response.body).to include(articles.first.title)
      end
    end

    context 'HTMX request' do
      it 'returns only the list fragment' do
        get articles_path, headers: { 'HX-Request' => 'true' }
        expect(response).to have_http_status(:ok)
        expect(response.body).not_to include('<html')
        expect(response.body).to include(articles.first.title)
      end
    end
  end

  describe 'infinite scroll' do
    it 'loads next page fragment' do
      get articles_path(page: 2), headers: { 'HX-Request' => 'true' }
      
      # Verify the response contains the trigger for the next page
      expect(response.body).to include('hx-trigger="revealed"')
      expect(response.body).to include('page=3')
    end
    
    it 'omits the scroll trigger on the last page' do
      # Create exactly enough articles to fill page 2
      get articles_path(page: last_page), headers: { 'HX-Request' => 'true' }
      expect(response.body).not_to include('hx-trigger="revealed"')
    end
  end
end

Performance Testing for SSR + HTMX

HTMX apps make more server requests than SPAs (every interaction is an HTTP round-trip). Measure response times for critical fragments:

import time
from django.test import TestCase

class FragmentPerformanceTests(TestCase):
    def test_article_list_fragment_under_100ms(self):
        # Warm up the database connection
        self.client.get('/articles/', HTTP_HX_REQUEST='true')
        
        start = time.time()
        for _ in range(10):
            response = self.client.get('/articles/', HTTP_HX_REQUEST='true')
        elapsed = (time.time() - start) / 10  # average
        
        self.assertLess(elapsed, 0.1, f'Fragment took {elapsed:.3f}s average (>100ms)')

Testing Caching Behavior

Fragment caching is a major HTMX optimization. Test that your cache headers are correct:

def test_article_list_fragment_is_cacheable(self):
    response = self.client.get(
        '/articles/',
        HTTP_HX_REQUEST='true'
    )
    
    # Verify cache headers for public, cacheable fragments
    self.assertIn('Cache-Control', response)
    self.assertIn('max-age', response['Cache-Control'])

def test_personalized_fragment_is_not_cached(self):
    self.client.force_login(self.user)
    response = self.client.get(
        '/dashboard/',
        HTTP_HX_REQUEST='true'
    )
    
    # User-specific content must not be publicly cached
    cache_control = response.get('Cache-Control', '')
    self.assertIn('private', cache_control)

End-to-End Browser Testing

After server-side tests, run Playwright tests to verify the full client-server integration:

test('infinite scroll loads more articles', async ({ page }) => {
  await page.goto('/articles');

  const initialCount = await page.locator('[data-testid="article-item"]').count();

  // Scroll to the bottom to trigger HTMX infinite scroll
  await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));

  // Wait for new articles to load
  await page.waitForFunction(
    (initial) => document.querySelectorAll('[data-testid="article-item"]').length > initial,
    initialCount
  );

  const newCount = await page.locator('[data-testid="article-item"]').count();
  expect(newCount).toBeGreaterThan(initialCount);
});

CI Pipeline for HTMX SSR Testing

A complete CI pipeline for an HTMX SSR app:

name: HTMX SSR Tests
on: [push, pull_request]

jobs:
  unit-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Run template unit tests
        run: python manage.py test tests.unit.templates

      - name: Run view unit tests
        run: python manage.py test tests.unit.views

  integration-tests:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:15
        env:
          POSTGRES_DB: testdb
          POSTGRES_USER: test
          POSTGRES_PASSWORD: test
    steps:
      - uses: actions/checkout@v4
      - name: Run request/response tests
        run: python manage.py test tests.integration

  e2e-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Start server
        run: python manage.py runserver &
      - name: Wait for server
        run: npx wait-on http://localhost:8000
      - name: Run Playwright tests
        run: npx playwright test

Monitoring HTMX SSR in Production

Server-side rendering issues don't always surface as errors. A slow database query, a template rendering the wrong fragment, or a missing HTMX attribute — these fail silently from the server's perspective.

HelpMeTest runs browser-level tests against your live application on a schedule. It makes HTMX requests, inspects the fragments returned, and alerts you if the HTML structure changes or interactions break. No server-side instrumentation needed — it monitors the behavior your users experience.

Summary

Testing HTMX SSR applications requires coverage at three levels:

  1. Template unit tests — fast, isolated, verify HTML structure and HTMX attributes
  2. Request/response integration tests — verify the HX-Request header routing, response headers, and fragment content
  3. End-to-end browser tests — verify the full HTMX exchange including DOM swaps

The key insight: in HTMX apps, your server logic is your frontend logic. Test the server thoroughly, and the client-side behavior mostly takes care of itself.

Read more

Start now free