Blog
Django: How to send request to JSON view in tests
Vera Mazhuga
Vera Mazhuga
Software DeveloperIf in your Django project you have a view that accepts or returns JSON, you can use the following code for your unittests
import json
from django.test import TestCase
class JSONViewTestCase(TestCase):
def test_json_view(self):
response = self.client.post(
reverse(
'my_json_view',
args=('test', 123)
),
json.dumps({
'user': 'me@example.com',
}),
'json',
HTTP_X_REQUESTED_WITH='XMLHttpRequest',
)
json_string = response.content
response_data = json.loads(json_string)
# do smth.Written by Vera Mazhuga
Vera Mazhuga
Vera specializes in writing and maintaining code for various applications. Her focus on problem-solving and efficient programming ensures reliable and effective software solutions.
Stay ahead of what's next.
Get fresh ideas, insights, and practical perspectives on AI, technology, and digital products, straight to your inbox.
We respect your inbox. Privacy policy