'Django TestCase: does it make sens to test Ajax view using TestCase?

EDIT 07/04/2022

As mentionned in the title, maybe test I want to run have no sens as it is an ajax view?

I start reading about tierce librairies to tests Django web project (Sinon.Js, Mocha, etc...) but it add another 'abstraction', another tool and will not help me understand what happen...


EDIT 04/04/2022 16:30

I have try to change my Ajax CBV to an Ajax FBV with simple inputs (not using form) but doesn't change and still have empty POST.get in my view

reading different post and tutoriel I can not figure out what is going wrong with my test.

data sent in client.post() are retrieved in view with self.request.body that mean that datas seems to be sent but not on properly format. I've try many format neither works...

hope some help because make me crazy...

# requête Ajax function 
def AjaxPatientCreateFunction(request):

    if request.method == "POST" and request.is_ajax():
        pat = request.POST.get('pat')         # still empty
        pat_sit = request.POST.get('pat_sit') # still empty

    return JsonResponse({"success":True}, status=200)

EDIT 01/04/2022 15:00

I have worked on another test for a 'normal' CBV CreateView and it works

class VisiteCreateViewTest(TestCase):

     def setUp(self):     
         # Create data
         create_test_data()
         # login
         self.login = self.client.login(username='admin', password='admin')  

     def test_create_visite(self):
        
         # login verification
         self.assertTrue(self.login)

         print('number of visit form before',Visite.objects.count())
         response = self.client.post(
             reverse('ecrf:visite_create', kwargs={"pk": 1}), 
             data={"pat":1,"vis_dat": '2022-04-01',},
             follow=True
         )
         self.assertTrue(200,response.status_code)


EDIT 01/04/2022

I first post on home page to call context_processor but data form client is still empty in my ajax view

I post JS below


EDIT

seems that my custom data_context_processor is nerver called in test


I want to implent test of one of my Ajax view.

I have read the doc but don't know why data are not pass to the form, and consequently form validation fail, explaining status_code 400.

views.py

class AjaxPatientCreate(SuccessMessageMixin, CreateView): 

    model = Patient
    form_class = PatientForm

    def get(self, *args, **kwargs):
        form = self.form_class()
        return render(self.request, self.template_name, {"PatientForm": form})

    def post(self, *args, **kwargs):
        if self.request.method == "POST" and self.request.is_ajax():
            pat = self.request.POST.get('pat')                        # empty
            pat_sit = self.request.POST.get('pat_sit')                # empty
            form = self.form_class(self.request.POST)

            if form.is_valid():
                form.save()
                return JsonResponse({
                    "success":True,
                    "total_patient": Patient.objects.filter(pat_sit__in = user_authorized_sites).count(),  
                    "datatable": render_to_string(
                        'ecrf/_datatable.html',
                        {
                            'ajax_patients': Patient.objects.filter(pat_sit__in = user_authorized_sites),
                            'user_can_delete_patient' : self.request.user.has_perm('ecrf.can_delete_patient')
                        } # data to pass to template
                    )
                }, status=200)
            else:
                return JsonResponse({"success":False}, status=400)

test.py

@override_settings(DEBUG=True)
class AjaxPatientCreateViewTest(TestCase):

    def setUp(self):
        self.client = Client(HTTP_ACCEPT_LANGUAGE='fr') # define in context_processor      
        self.login = self.client.login(username='admin', password='admin')
    
    def test_post(self):
        self.assertTrue(self.login)

        self.client.post(reverse('home')) # to enter request/response cycle

        response = self.client.post(
            reverse('ecrf:ajax_patient_create'), 
            data={'pat': 'TR001','pat_sit': 4,},
            content_type='application/json', # django serialize data to JSON
            HTTP_X_REQUESTED_WITH='XMLHttpRequest' # ajax view
        )
        print('response.status_code',response.status_code)

script.js

$("#patient_create_form").submit(function (e) {
    e.preventDefault();
    console.log('domain', domain)
    var serializedData = $(this).serialize();
    $.ajax({
        type: 'POST',
        url: url_patient_create,
        data: serializedData, 
        dataType: 'html',
        success: function (response) {
            obj = JSON.parse(response);
            console.log('Success - message', obj.message);
        },
        error: function (response) {
            console.log('Error', response)
            //console.log('serializedData',serializedData);
        }
    });
});


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source