Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - testing view which works with ajax requests

I want to test that my view returns correct json after processes. here is my view:

@login_required
@require_POST
def xxx_view(request):
    if 'post_id' in request.POST:
        post_id = request.POST['post_id']

        post = Post.objects.get(id=post_id)
        post.order = 2
        post.save()

        json_dump = simplejson.dumps({'new_title': post.order,})
        return HttpResponse(json_dump, mimetype='application/json')
    else:
        return HttpResponse('oups')

this works correctly. Here is what i ve tried for testing:

from django.test import TestCase
from django.test.client import Client
from django.utils import simplejson
from app.models import *

c = Client()
class CustomTests(TestCase):
    def test_xxx(self):
        json_data = simplejson.dumps({'post_id': 1,})

        response = client.post('/content/vote/', json_data,
                content_type='application/json',
                HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 302) # this is OK.
        self.assertEqual(response.content, 2) # but this fails.

response.content returns empty string.

Thank you.

like image 906
alioguzhan Avatar asked Dec 15 '22 10:12

alioguzhan


1 Answers

If you are testing it using django.test module.

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 X-REQUESTED_WITH header is equal to 'XMLHttpRequest', a standard that's supported by most javascript libraries.

from django.test.client import Client
client = Client()
client.post("http://example.com", {"foo": "bar"}, **{'HTTP_X_REQUESTED_WITH': 
'XMLHttpRequest'})

Please note that is_ajax is deprecated in Django 3.1, and will be removed from Django at a later version.

like image 113
Amanpreet Avatar answered Jan 19 '23 03:01

Amanpreet