[Django]-Testing Graphene-Django

4👍

I’ve been writing tests that do have a big block of text for the query, but I’ve made it easy to paste in that big block of text from GraphiQL. And I’ve been using RequestFactory to allow me to send a user along with the query.

from django.test import RequestFactory, TestCase
from graphene.test import Client

def execute_test_client_api_query(api_query, user=None, variable_values=None, **kwargs):
    """
    Returns the results of executing a graphQL query using the graphene test client.  This is a helper method for our tests
    """
    request_factory = RequestFactory()
    context_value = request_factory.get('/api/')  # or use reverse() on your API endpoint
    context_value.user = user
    client = Client(schema)  # Note: you need to import your schema
    executed = client.execute(api_query, context_value=context_value, variable_values=variable_values, **kwargs)
    return executed

class APITest(TestCase):
    def test_accounts_queries(self):
        # This is the test method.
        # Let's assume that there's a user object "my_test_user" that was already setup
        query = '''
{
  user {
    id
    firstName
  }
}
'''
        executed = execute_test_client_api_query(query, my_test_user)
        data = executed.get('data')
        self.assertEqual(data['user']['firstName'], my_test_user.first_name)
        ...more tests etc. etc.

Everything between the set of ”’ s ( { user { id firstName } } ) is just pasted in from GraphiQL, which makes it easier to update as needed. If I make a change that causes a test to fail, I can paste the query from my code into GraphQL, and will often fix the query and paste a new query back into my code. There is purposefully no tabbing on this pasted-in query, to facilitate this repeated pasting.

Leave a comment