Testing AJAX Requests in Django

Django has a really handy function on the request object that will determine if the request was an AJAX request (an XMLHttpRequest).

request.is_ajax()

It simply checks whether the HTTP_X_REQUESTED_WITH header is equal to ‘XMLHttpRequest’, a standard that’s supported by most javascript libraries. You can read more about it and see the list of supporting frameworks here.

It’d be great if the Django client had a simple client.ajax request in addition to its client.post and client.get requests, but alas it doesn’t.  The tests can still be done however by changing the HTTP_X_REQUESTED_WITH header when sending  your test requests.

>>> from django.test.client import Client
>>> client = Client()

>>> client.post(“http://example.com”, {“foo”: “bar”}, **{‘HTTP_X_REQUESTED_WITH’: ‘XMLHttpRequest’})

From there its fairly straight forward to create your own .ajax wrapper if you’d like.

Now you have no excuse for not having complete tests for all of your XMLHttpRequests :).

Advertisements
1 comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s