Skip to content
Advertisement

Django Rest Framework JWT Unit Test

I am using DRF with the JWT package for authentication. Now, I’m trying to write a unit test that authenticates itself with a JWT token. No matter how I try it, I can’t get the test API client to authenticate itself via JWT. If I do the same with an API client (in my case, Postman), everything works.

This is the test case:

JavaScript

But I always get a 401 Authentication credentials were not provided.

In response.request I see the token is there, it’s just not being applied I guess.

If I rewrite the test to use rest_framework.test.RequestsClient and actually send it to the live_server URL, it works.

Any help on this?

P.S.: I am aware of force_authenticate() and login, but I would like my unit tests to access the API the same as the API client will in production.

Advertisement

Answer

Try setting up a new APIClient for this test. This is how my own test looks like

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement