Testing Django REST framework endpoints

django testing drf django rest framework

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 unittest
from django.contrib.auth import get_user_model
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from jobs.models import Job
User = 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/{}/')
# check status
self.assertEqual(response.status_code, status.HTTP_200_OK)
# check data
self.assertEqual(['name'], 'Typescript Developer')