</>
Django REST Framework - Array in a payload is not received when unit testing
Problem statement
When sending data in Django REST framework in a unit test, all data are recieved correctly apart from those
with list
type.
class JobsAPITestCase(TestCase):def setUp(self):User.objects.create_user(username='test', password='test-pass')self.client = APIClient()self.client.login(username='test', password='test-pass')def test_job_can_be_created(self):response = self.client.post(f'/api/jobs/', {"name": "Test",# TODO - for some reason, tags is not in validated_data in tests# however it's present in real app"tags": [{"id": 2, "label": "Backend"},]})
Solution
The solution was to pass format=json
to the post
method.
The following snippet works:
class JobsAPITestCase(TestCase):def setUp(self):User.objects.create_user(username='test', password='test-pass')self.client = APIClient()self.client.login(username='test', password='test-pass')def test_job_can_be_created(self):response = self.client.post(f'/api/jobs/', {"name": "Test","tags": [{"id": 2, "label": "Backend"},]}, format="json")# tags should be present in validated_data now