Home > Mobile >  How to test an HTMX Get request?
How to test an HTMX Get request?

Time:06-03

I'm working with Django and HTMX. One of my views receives a GET request and returns a whole page. However, if that GET request is from an HTMX element, the view will return a fragment:

from django.shortcuts import render

def view_example(request):
    if request.htmx:
        return render(request, 'fragment.html')
    else:
        return render(request, 'page.html')

In page.html an HTMX element triggers a GET request that expects this fragment. It works - my functional tests see the result of the HTMX request. When I view it in the browser it also works. It doesn't work in my unit tests, though!

I'm trying to test the two different types of responses:

from django.test import TestCase

class TestRequests(TestCase):
    def test_page(self):
        response = self.client.get('/')
        self.assertTemplateUsed(response, 'page.html')

    def test_fragment(self):
        headers = {'Hx-Request': 'true'}
        response = self.client.get('/', **headers)
        self.assertTemplateUsed(response, 'fragment.html')

test_page passes, as expected, but test_fragment fails:

AssertionError: False is not true : Template 'fragment.html' was not a template used to render the response. Actual template(s) used: page.html

How do I simulate an HTMX request so that I can test my fragment logic?

CodePudding user response:

Django-HTMX's header checking is case sensitive (it's a dict key lookup). You have to set HX-Request header with capital HX:

def test_fragment(self):
    headers = {'HX-Request': 'true'}
    response = self.client.get('/', **headers)
    self.assertTemplateUsed(response, 'fragment.html')
  • Related