pythondjangographqlgraphene-djangodjango-graphql-jwt

How to authenticate with django-grahql-jwt in a graphene-django GraphQLTestCase?


I'm trying to test my mutation according to graphene django documentation. the mutation works with @login_required decorator and there's a problem because any method of login to test doesn't work. I tried with self.client.login, self.client.force_login. I've even made a tokenAuth mutation, and hardcoded some credentials there and it also doesn't work; the user is still Anonymous.

def test_create_member_mutation(self):
    response = self.query(
        '''
        mutation createMember($firstName: String) {
            createMember(firstName: $firstName) {
                member {
                    id
                }
            }
        }
        ''',
        op_name='createMember',
        variables={'firstName': 'Foo'}
    )

    self.assertResponseNoErrors(response)

Solution

  • This is how I've solved it in my tests:

    You can pass a token that has been made for the test user in the headers keyword argument of self.query():

    from django.contrib.auth import get_user_model
    from graphene_django.utils import GraphQLTestCase
    from graphql_jwt.shortcuts import get_token
    
    
    class ExampleTests(GraphQLTestCase):
    
        def test_create_member_mutation(self):
            user = get_user_model().objects.get(pk=1)
            token = get_token(user)
            headers = {"HTTP_AUTHORIZATION": f"JWT {token}"}
    
            graphql = '''
                mutation createMember($firstName: String) {
                    createMember(firstName: $firstName) {
                        member {
                            id
                        }
                    }
                }
            '''
    
            response = self.query(
                graphql,
                op_name='createMember',
                variables={'firstName': 'Foo'},
                headers=headers,
            )
            self.assertResponseNoErrors(response)