Ajax Request in Django Test Client

Here is code snippet to perform ajax request in django test client.

from django.test import TestCase
from django.test.client import Client

class MyTestCase(TestCase):

    def setUp(self):
        c = Client()

    def test_ajax_post(self):
        payload = {'name': 'John Doe', 'age': 25}
        response = self.c.post('/create_url/', payload, HTTP_X_REQUESTED_WITH='XMLHttpRequest')

        self.assertEquals(response.status_code, 200)   

You have to log in to your apps before performing this request. You can setup your authentication on setUp method. If you don’t your request will redirected and you will get 302 status code then it will fail your unit test.

Actually this post is reposted from my another blog, I just need to add more content to my new blog. 😀

Reference: http://adiyat.polatic.me/django-testing-client-with-ajax/

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.