</>
Testing Django REST framework endpoints
This example lets you bootstrap unit tests for Django REST framework. The main point is to create an user and a client and authenticate using the client.
Afterwards, everything works as expected.
import unittestfrom django.contrib.auth import get_user_modelfrom django.test import TestCasefrom rest_framework import statusfrom rest_framework.test import APIClientfrom jobs.models import JobUser = get_user_model()class ExampleTestCase(TestCase):def setUp(self):User.objects.create_user(username='test', password='test-pass')self.job = Job.objects.create(name="Typescript Developer")self.client = APIClient()self.client.login(username='test', password='test-pass')def test_job_is_returned_by_api(self):response = self.client.get(f'/api/jobs/{self.job.id}/')# check statusself.assertEqual(response.status_code, status.HTTP_200_OK)# check dataself.assertEqual(response.data['name'], 'Typescript Developer')self.assertEqual(response.data['id'], self.job.id)