graphqljestjsgraphql-jsgraphql-tag

How to test GraphQL queries with fragments using jest


Problem: I would like to test a GraphQL query that lives in a .graphql file like this:

#import '../../fragments/Widget.graphql'

query WidgetFragment($id: ID) {
    readWidgetFragment(id: $id) {
        ...Widget
    }
}

To create a GraphQL schema with mocked resolvers and data, I use makeExecutableSchema and addMockFunctionsToSchema from graphql-tools.

To run the query from inside a jest test, my understanding is that I need to use the graphql() function from graphql-js.

This function needs the query as a string, so I tried two different ways, but neither of them worked:


Solution

  • You can use this:

    import { print } from 'graphql/language/printer'
    
    import query from './query.gql'
    
    ...
    
    print(query)