2

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)
ruohola
  • 21,987
  • 6
  • 62
  • 97
Sevy
  • 93
  • 10

1 Answers1

6

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
                    }
                }
            }
        '''

        respsone = self.query(
            graphql,
            op_name='createMember',
            variables={'firstName': 'Foo'},
            headers=headers,
        )
        self.assertResponseNoErrors(response)
ruohola
  • 21,987
  • 6
  • 62
  • 97
  • I get: `TypeError: query() got an unexpected keyword argument 'headers'`, what versions of graphql and graphene do you have installed ? I read all the source code and found only `**extra`, no mention of headers. – Emacs The Viking Jun 03 '21 at 10:38
  • @EmacsTheViking The parameters seems to be there still: https://github.com/graphql-python/graphene-django/blob/623d0f219ebeaf2b11de4d7f79d84da8508197c8/graphene_django/utils/testing.py#L75 – ruohola Jun 03 '21 at 11:32
  • 1
    Thanks ! I don't know why I didn't check the version before. I have 2.7.1 which is very old now, I joined the project and it was created a good while ago... I will upgrade. Thankyou. – Emacs The Viking Jun 04 '21 at 12:12