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:
.graphql
file as a normal text file, giving me the raw string (using the jest-raw-loader in my jest config).
This gives me: Failed: Errors in query: Unknown fragment "Widget".
when I run the query..graphql
file into a query
object using jest-transform-graphql. I believe this should be the right approach, because it should resolve any imported fragments properly. However, to execute the query, I need to pass query.loc.source.body
to the graphql
, which results in the same error message as option 1.You can use this:
import { print } from 'graphql/language/printer'
import query from './query.gql'
...
print(query)