Home > Software engineering >  how can i create unit tests a view that returns data in json in django
how can i create unit tests a view that returns data in json in django

Time:07-01

I was wondering how I can create unit tests for a view like this. I have several of these in my project.

def json_list_user(request):
    data = list(Us.objects.values())
    
    return JsonResponse(data, safe=False)

CodePudding user response:

You can use self.client.get() and check what data the response holds, starting with status_code.

class MyTestCase(TestCase):
    def test_json_list_user_response_status_code(self):
        response = self.client.get(reverse_lazy("namespace_of_your_view"))
        self.assertEqual(response.status_code, 200)

You can also check if data sent is as expected:

    def setUp(self):
        # create an object or few objects here
        Us.objects.create()

    def test_json_list_user_correct_list(self):
        response = self.client.get(reverse_lazy("namespace_of_your_view"))
        # check if response.json() have proper object/-s
  • Related