When writing unit tests for your GraphQL API endpoints in Django, testing operations that require authentication (like modifying shopping carts or checking out orders) can be difficult. If your backend uses JWT-based middleware decorators, you have to generate valid tokens, inject auth headers, and mock external identity servers for every test run.
A cleaner testing strategy is to use Python's built-in unittest.mock to mock the auth decorator directly, bypassing verification checks during test execution.
1. The Mocking Challenge
GraphQL libraries (like django-graphql-jwt) use decorators like @login_required to restrict resolvers. If we mock this decorator before importing our schema or running queries, the mock replaces the decorator logic, letting us query the resolver as any mock user:
import unittest
from unittest import mock
from django.test import Client
class GraphQLAuthTest(unittest.TestCase):
def setUp(self):
self.test_client = Client()
@mock.patch("graphql_jwt.decorators.login_required")
def test_delete_account_resolver(self, login_required_mock):
# By setting the mock side effect, we bypass the decorator validation
login_required_mock.side_effect = lambda x: x
data = {
"operationName": "DeleteCustomerAccount",
"variables": {"input": "test_user@cpunto.com"},
"query": "mutation DeleteCustomerAccount($input: String!) { deleteCustomerAccount(emailAddress: $input) }"
}
res = self.test_client.post("/store", json=data)
self.assertIn("data", res.json())
2. Benefits of Decorator Mocking
Mocking the decorator isolates your tests: you verify that the resolver logic works under the assumption of successful login, without coupling test outcomes to authentication signature variables.